다음 코드는 김종권의 iOS 앱 개발 알아가기 블로그로부터 참고하였습니다.

 

 

LoadingService에서 showLoading은 로딩중임을 알리는 Indicator가 화면에 표시되게 만들어주는 메서드이다. 최상단의 뷰를 가져와서 그 위에 Indicator를 표시하며, 이미 표시중인 indicator가 있는 경우 그것을 그대로 사용한다. 

 

import Foundation
import UIKit

class LoadingService {
    static func showLoading() {
        DispatchQueue.main.async {
            // 아래 윈도우는 최상단 윈도우
            guard let window = UIApplication.shared.windows.last else { return }

            let loadingIndicatorView: UIActivityIndicatorView
            // 최상단에 이미 IndicatorView가 있는 경우 그대로 사용.
            if let existedView = window.subviews.first(
            	where: { $0 is UIActivityIndicatorView } ) as? UIActivityIndicatorView {
                loadingIndicatorView = existedView
            } else { // 새로 만들기.
                loadingIndicatorView = UIActivityIndicatorView(style: .large)
                // 아래는 다른 UI를 클릭하는 것 방지.
                loadingIndicatorView.frame = window.frame
                loadingIndicatorView.color = .brown

                window.addSubview(loadingIndicatorView)
            }
            loadingIndicatorView.startAnimating()
        }
    }

    static func hideLoading() {
        DispatchQueue.main.async {
            guard let window = UIApplication.shared.windows.last else { return }
            window.subviews.filter({ $0 is UIActivityIndicatorView })
            	.forEach { $0.removeFromSuperview() }
        }
    }
}​
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기
// custom