Computer >> 컴퓨터 >  >> 프로그래밍 >> iOS

Swift에서 MBProgressHUD를 손쉽게 사용하는 방법

MBProgressHUD는 iOS 앱에서 로딩 인디케이터나 진행 상태를 표시할 때 널리 사용되는 오픈소스 라이브러리입니다. Swift 프로젝트에서 MBProgressHUD를 사용하려면 먼저 Podfile이 없는 경우 새로 생성해야 합니다.

터미널을 열고 프로젝트 디렉터리로 이동한 뒤 CocoaPods를 초기화하고, 이어서 MBProgressHUD를 설치합니다.

cd /projectDirectory
pod init
open podfile

Podfile이 열리면 아래 한 줄을 추가합니다. 그다음 터미널로 돌아가 같은 디렉터리에서 설치 명령어를 실행하세요.

pod 'MBProgressHUD', '~> 1.1.0'
pod install

위 명령어를 모두 실행하면 MBProgressHUD가 프로젝트에 설치됩니다. 이후에는 필요한 ViewController에서 라이브러리를 import하여 바로 사용할 수 있고, UIViewController의 extension을 만들어 앱 전역에서 재사용하는 방식도 가능합니다.

지금부터 두 가지 방법을 살펴보겠습니다. 두 방법 모두 동일한 결과를 보여줍니다.

1. viewDidLoad에 직접 추가하기

let Indicator = MBProgressHUD.showAdded(to: self.view, animated: true)
Indicator.label.text = "Indicator"
Indicator.isUserInteractionEnabled = false
Indicator.detailsLabel.text = "fetching details"
Indicator.show(animated: true)

마찬가지로 아래 코드를 호출하면 화면에서 인디케이터를 숨길 수 있습니다.

MBProgressHUD.hide(for: self.view, animated: true)

같은 기능을 구현하는 두 번째 방법도 확인해 보겠습니다.

2. Extension으로 전역에서 사용할 수 있게 만들기

여러 화면에서 반복적으로 로딩 인디케이터를 사용해야 한다면, UIViewController의 extension으로 메서드를 분리해 두는 것이 효율적입니다.

extension UIViewController {
    func showIndicator(withTitle title: String, and Description:String) {
        let Indicator = MBProgressHUD.showAdded(to: self.view, animated: true)
        Indicator.label.text = title
        Indicator.isUserInteractionEnabled = false
        Indicator.detailsLabel.text = Description
        Indicator.show(animated: true)
    }
    func hideIndicator() {
        MBProgressHUD.hide(for: self.view, animated: true)
    }
}

이렇게 작성해 두면 어떤 ViewController에서든 showIndicator(withTitle:and:)hideIndicator()만 호출하면 되므로 코드 중복을 크게 줄일 수 있습니다.

위 방법 중 하나를 실제 기기에서 실행하면 다음과 같은 결과를 확인할 수 있습니다.

Swift에서 MBProgressHUD를 손쉽게 사용하는 방법