无法使用协变类型 'UIRefreshControl' 覆盖类型 'UIRefreshControl?' 的可变 属性 'refreshControl'

Cannot override mutable property 'refreshControl' of type 'UIRefreshControl?' with covariant type 'UIRefreshControl'

我在我的表视图中使用 UIRefreshControl 来提取新数据。但是当我定义控件时,下面的错误显示。我用谷歌搜索了一段时间,但没有找到有用的东西。

我使用Xcode版本9.2(9C40b),swift4,IOS11.2

Cannot override mutable property 'refreshControl' of type 'UIRefreshControl?' with covariant type 'UIRefreshControl'

var refreshControl = UIRefreshControl()

如果要定义另一个控件,请更改名称...refreshControl 是自 iOS10/iOS6 [分别] 以来的 UIScrollView/UITableViewController ivar。您正在尝试重新定义它,这就是导致错误的原因。或者你当然可以使用提供的那个。

你的意思可能是 self.refreshControl = UIRefreshControl()

编译器阻止您在子类中指定比超类设置的要求更严格的要求。

假设编译器允许您使用非 Optional 类型覆盖 Optional 属性。如果有人这样做会怎样:

let tableView: UITableView = CoolTableViewSubclass()
tableView.refreshControl = nil // but my overridden property can't be nil!

作为小班,当有人把你当作超班时,你需要好好工作。所以在这种情况下编译器会阻止你,因为它已经知道你违反了这条规则。

Mike Ash wrote this up in an unsurprisingly good post if you're curious.

Swift 4/5

override func viewDidLoad() {
    super.viewDidLoad()

    self.refreshControl = UIRefreshControl()
    self.refreshControl!.attributedTitle = NSAttributedString(string: "Pull to refresh")
    self.refreshControl!.addTarget(self, action: #selector(refresh(sender:)), for: UIControl.Event.valueChanged)

}

@objc func refresh(sender:AnyObject) {
   // Code to refresh table view

    self.refreshControl!.endRefreshing()
}