如何用 Swift 使用 MBProgressHUD?


在 Swift 中使用 MBProgressHUD 需先建立一個 podfile(如果尚不存在)。

開啟終端,將目錄更改為專案目錄,然後初始化 pod,接著安裝 MBProgressHUD。

cd /projectDirectory
pod init
open podfile

然後在 podfile 中新增以下行,回到終端,然後在同一目錄中執行以下命令。

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

執行完這些命令後,MBProgressHUD 將安裝到你的專案中,現在可以在 ViewController 中匯入此庫,或者你可以建立一個 UIView 控制器的擴充套件,並使用此方法。

讓我們透過兩種不同的方法來實現此目的,這兩種方法都會產生相同的結果。

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 {
   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)
   }
}

當我們在裝置上執行其中任何一個命令時,會得到以下結果。

更新於: 2019 年 7 月 30 日

1 千+ 檢視

開啟你的 職業

完成課程,獲得認證

開始
廣告