我想创建协议,这使我能够在UIViewController及其子类符合此协议时向/从UIViewController及其子类添加/删除活动指示符。
所以我最终得到了像这样的代码
protocol ActivityIndicatorPresenter {
var activityIndicator: UIActivityIndicatorView { get }
func showActivityIndicator()
func hideActivityIndicator()
}
extension ActivityIndicatorPresenter where Self: UIViewController {
func showActivityIndicator() {
dispatch_async(dispatch_get_main_queue()) {
self.activityIndicator.color = UIColor.blackColor()
self.activityIndicator.frame = CGRect(x: 0.0, y: 0.0, width: 80.0, height: 80.0)
self.activityIndicator.center = CGPoint(x:self.view.bounds.size.width / 2, y:self.view.bounds.size.height / 2)
self.view.addSubview(self.activityIndicator)
self.activityIndicator.startAnimating()
}
}
func hideActivityIndicator() {
dispatch_async(dispatch_get_main_queue()) {
self.activityIndicator.stopAnimating()
self.activityIndicator.removeFromSuperview()
}
}
}
并在UIViewController的子类中:
class MyViewController: ActivityIndicatorPresenter {
var activityIndicator: UIActivityIndicator { get {return self.spinner}}
var spinner = UIActivityIndicator()
}
一切正常,但我认为在计算属性的getter中返回存储属性是一种解决方法。它是更漂亮的实现方式吗?