我正在尝试提取一些代码库以供重用。我的方法是使用 Protocol
和 Protocol
Extension
而不是一般的 BaseClass
。
我在下面创建了一个协议(protocol)
和协议(protocol)扩展
protocol MovieDisplay {
var collectionView: UICollectionView! { get set }
var refreshControl: UIRefreshControl! { get set }
}
extension MovieDisplay where Self: UIViewController {
var refreshControl: UIRefreshControl {
let rc = UIRefreshControl()
rc.backgroundColor = .clear
rc.tintColor = .lightGray
if #available(iOS 10.0, *) {
collectionView.refreshControl = rc
} else {
// Fallback on earlier versions
collectionView.addSubview(rc)
}
return rc
}
}
在采用协议(protocol)的主类中,我这样声明(使用 refreshcontrol
的默认实现)
class PopularMovieVC: UIViewController, MovieDisplay {
@IBOutlet weak var collectionView: UICollectionView!
}
问题是涉及refreshcontrol
的功能不起作用。只有当我在主类中显式声明 refreshcontrol
变量并将扩展转换为函数并在主类中调用它时,它才有效,如下所示:
func setupRefreshControl() {
refreshControl.backgroundColor = .clear
refreshControl.tintColor = .lightGray
if #available(iOS 10.0, *) {
collectionView.refreshControl = refreshControl
} else {
// Fallback on earlier versions
collectionView.addSubview(refreshControl)
}
}
如何为默认实现正确配置协议(protocol)
和协议(protocol)扩展
?
最佳答案
它不起作用,因为未隐式调用计算属性。
在 viewDidLoad
中添加这一行应该初始化刷新控件
_ = refreshControl
在这种情况下,我真的更喜欢基类
关于快速正确使用协议(protocol)扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53525665/