LoginSignup
4
2

More than 5 years have passed since last update.

【Xcode】UIActivityIndicatorViewをextensionにして簡単にぐるぐるを表示する

Posted at

UIActivityIndicatorViewを簡単に表示したい

001.png

こういうぐるぐるを表示したくて調べたら、こちら↓の記事を見つけました。

LoadingView表示用のUIViewのExtensionを作る

ありがとうございます!

UIViewControllerのextensionにしてみた

記事を参考にして、 UIActivityIndicatorView を UIViewController の extension にしてみました。

 extension UIViewController {

     func showLoading(style indicatorStyle: UIActivityIndicatorView.Style) {
         let overLayView = LoadingOverlayView(frame: view.frame, indicatorStyle: indicatorStyle)
         view.addSubview(overLayView)
         DispatchQueue.main.async {
             overLayView.startAnimation()
         }
     }

     func hideLoading() {
         view.subviews.forEach { subView in
             if let subView = subView as? LoadingOverlayView {
                 DispatchQueue.main.async {
                     subView.stopAnimation()
                     subView.removeFromSuperview()
                 }
             }
         }
     }

 }

 fileprivate final class LoadingOverlayView: UIView {

     private var indicatorView: UIActivityIndicatorView!

     init(frame: CGRect, indicatorStyle: UIActivityIndicatorView.Style) {
         super.init(frame: frame)

         indicatorView = UIActivityIndicatorView(style: indicatorStyle)
         indicatorView.hidesWhenStopped = true
         addSubview(indicatorView)
         indicatorView.center = center
         backgroundColor = UIColor.black
         alpha = 0.5
     }

     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }

     func startAnimation() {
         indicatorView.startAnimating()
     }

     func stopAnimation() {
         indicatorView.stopAnimating()
     }

 }

UIActivityIndicatorViewを表示するには

UIActivityIndicatorViewを表示するには、 ViewController の好きなところで showLoading 呼び出すだけです。

止めるときには、 hideLoading を呼び出してください。

     func showActivityIndicator() {
         showLoading(style: .whiteLarge)
     }

     func hideActivityIndicator() {
         hideLoading()
     }
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2