快速正确使用协议(protocol)扩展

标签 swift protocols protocol-extension

我正在尝试提取一些代码库以供重用。我的方法是使用 ProtocolProtocol 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/

相关文章:

objective-c - SCLAlertView 未显示

swift - 在 do{}catch{} 之外使用变量/常量 - swift2

ios - 快速检查类是否具有封装协议(protocol)

swift - 扩展不同类时出现 "Does not conform to protocol"错误

java - 如何在 Android(Java) 中使用 json 反斜杠

ios - 为什么 swift GCD 不能在 tableview cell imageView 中工作

swift - 是否可以在另一种协议(protocol)的扩展内实现一种协议(protocol)的功能?

swift - 如何在方法签名中使用泛型协议(protocol)?

swift - 'Equatable' 不能在扩展中自动合成

swift - 面向协议(protocol)编程扩展变量初始化两次