这是协议扩展的理想选择。我最近自己做了这个。
/// 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() } }