[swift] - 호출되는 Alamofire 네트워크 요청에 따라 Indicator의 위치를 자유롭게 설정하는 방법

Alamofire를 사용하여 네트워크 요청을 처리하는 경우, Indicator의 위치를 원하는대로 설정할 수 있습니다. 이번 글에서는 Indicator를 원하는 위치로 설정하는 방법에 대해 알아보겠습니다.

1. Indicator 설정하기

Indicator를 원하는 위치로 설정하기 위해서는 UIActivityIndicatorView를 사용하여 원하는 뷰에 Indicator를 추가해야 합니다. 먼저, Indicator를 표시할 뷰를 생성하고, 그 뷰에 Indicator를 추가하는 코드를 작성해야 합니다.

let indicatorView = UIActivityIndicatorView(style: .whiteLarge)
indicatorView.color = .black
indicatorView.center = view.center
view.addSubview(indicatorView)
indicatorView.startAnimating()

2. 네트워크 요청 전 Indicator 표시하기

Alamofire를 사용하여 네트워크 요청을 보내기 전에 Indicator를 표시해야 합니다. 이를 위해서는 요청 전에 Indicator를 추가한 뷰를 화면 상에 표시해야 합니다. 다음은 Indicator를 표시하고 네트워크 요청을 보내는 코드의 예시입니다.

indicatorView.startAnimating()

AF.request(url, method: .get).responseJSON { response in
    indicatorView.stopAnimating()
    
    // 네트워크 응답 처리
}

위의 예시 코드에서는 네트워크 요청을 보내기 전에 indicatorView.startAnimating()을 호출하여 Indicator를 시작하고, 요청 후에 indicatorView.stopAnimating()을 호출하여 Indicator를 정지합니다.

3. Indicator 위치 변경하기

위 코드에서 Indicator의 위치는 indicatorView.center = view.center로 설정되어 있습니다. 이 코드를 수정하여 Indicator의 위치를 원하는대로 변경할 수 있습니다. 예를 들어, Indicator를 화면의 오른쪽 상단에 위치시키려면 다음과 같이 코드를 수정합니다.

indicatorView.center = CGPoint(x: view.bounds.width - 30, y: 30)

위의 예시 코드에서는 Indicator를 뷰의 오른쪽 상단으로 이동시키기 위해 indicatorView.center를 수정하였습니다. 적절한 좌표 값을 설정하여 Indicator를 원하는 위치로 이동시킬 수 있습니다.

참고 자료