当前位置:  开发笔记 > IOS > 正文

Swift:在自定义类中启动和停止活动指示器的动画

如何解决《Swift:在自定义类中启动和停止活动指示器的动画》经验,为你挑选了1个好方法。



1> Guillermo Al..:

这是协议扩展的理想选择。我最近自己做了这个。

首先在文件中创建协议,例如ActivityIndi​​catorPresenter.swift

/// Used for ViewControllers that need to present an activity indicator when loading data.
public protocol ActivityIndicatorPresenter {

    /// The activity indicator
    var activityIndicator: UIActivityIndicatorView { get }

    /// Show the activity indicator in the view
    func showActivityIndicator()

    /// Hide the activity indicator in the view
    func hideActivityIndicator()
}

创建协议扩展名(在同一文件中或在另一个文件中)

public extension ActivityIndicatorPresenter where Self: UIViewController {

    func showActivityIndicator() {
        DispatchQueue.main.async {

            self.activityIndicator.activityIndicatorViewStyle = .whiteLarge
            self.activityIndicator.frame = CGRect(x: 0, y: 0, width: 80, height: 80) //or whatever size you would like
            self.activityIndicator.center = CGPoint(x: self.view.bounds.size.width / 2, y: self.view.bounds.height / 2)
            self.view.addSubview(self.activityIndicator)
            self.activityIndicator.startAnimating()
        }
    }

    func hideActivityIndicator() {
        DispatchQueue.main.async {
            self.activityIndicator.stopAnimating()
            self.activityIndicator.removeFromSuperview()
        }
    }
}

然后,任何视图控制器都可以遵守协议

class MyViewController: UIViewController, ActivityIndicatorPresenter {

/// Make sure to add the activity indicator
var activityIndicator = UIActivityIndicatorView()

//Suppose you want to load some data from the network in this view controller
override func viewDidLoad() {
    super.viewDidLoad()
    showActivityIndicator() //Wow you can use this here!!!
    getSomeData { data in 
        //do stuff with data
        self.hideActivityIndicator()
    }
}

推荐阅读
罗文彬2502852027
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有