muapps

iOSアプリ開発で得られた知見をメモ代わりに投稿します。

プログレスインジケータ実装

通信中にクルクルするやつ。

extension UIViewController {
  /// プログレスインジケータを表示する
  func displayProgressIndicator() {
    // UI更新はメインスレッドで行う
    DispatchQueue.main.async {
      let indicator = UIActivityIndicatorView(style: .whiteLarge)
      indicator.color = .gray

      let coverViewController = UIViewController()
      coverViewController.view.backgroundColor = .darkGray
      coverViewController.view.alpha = 0.9
      coverViewController.modalPresentationStyle = .overFullScreen
      indicator.center = coverViewController.view.center
      coverViewController.view.addSubview(indicator)

      self.present(coverViewController, animated: false, completion: nil)
      indicator.startAnimating()
    }
  }
  /// プログレスインジケータを閉じる
  func dismissProgressIndicator() {
    // UI更新はメインスレッドで行う
    DispatchQueue.main.async {
        self.presentedViewController?.dismiss(animated: false, completion: nil)
    }
  }
}

UIViewControllerを継承したクラスの中で

// プログレスインジケータ表示
self.displayProgressIndicator()
// プログレスインジケータ閉じる
self.dismissProgressIndicator()