ios - 在 Swift 中覆盖 UIScrollView 的委托(delegate)属性(就像 UICollectionView 一样)

标签 ios swift uiscrollview uiscrollviewdelegate

UIScrollView 有一个符合 UIScrollViewDelegate 的委托(delegate)属性

protocol UIScrollViewDelegate : NSObjectProtocol {
    //...
}
class UIScrollView : UIView, NSCoding {
    unowned(unsafe) var delegate: UIScrollViewDelegate?
    //...
}

UICollectionView 使用不同类型的 UICollectionViewDelegate 覆盖此属性

protocol UICollectionViewDelegate : UIScrollViewDelegate, NSObjectProtocol {
   //...
}

class UICollectionView : UIScrollView {
     unowned(unsafe) var delegate: UICollectionViewDelegate?
   //...
}

当我尝试像这样用我的协议(protocol)覆盖 UIScrollViews 委托(delegate)时:

protocol MyScrollViewDelegate : UIScrollViewDelegate, NSObjectProtocol {
    //...
}

class MyScrollView: UIScrollView {
    unowned(unsafe) var delegate: MyScrollViewDelegate?

}

编译器给了我两个警告:

  • 类型为“MyScrollViewDelegate?”的属性“delegate”?不能覆盖类型为“UIScrollViewDelegate?”的属性吗?
  • “unowned”不能应用于非类类型“MyScrollViewDelegate?”

我如何继承 UIScrollView 并覆盖委托(delegate)属性的类型(即使用自定义委托(delegate)协议(protocol))?

最佳答案

我认为覆盖继承的属性在 Objective-C 中是可能的,但在 Swift 中(至少目前)是不可能的。我处理这个问题的方法是将一个单独的委托(delegate)声明为正确类型的计算属性,该属性获取和设置实际委托(delegate):

@objc protocol MyScrollViewDelegate : UIScrollViewDelegate, NSObjectProtocol {
    func myHeight() -> CGFloat
    // ...
}

class MyScrollView: UIScrollView {
    var myDelegate: MyScrollViewDelegate? {
        get { return self.delegate as? MyScrollViewDelegate }
        set { self.delegate = newValue }
    }
}

这样调用 ScrollView 委托(delegate)的任何东西通常仍然有效,并且您可以在 self.myDelegate 上调用您的特定委托(delegate)方法,如下所示:

if let height = self.myDelegate?.myHeight() {
    // ...
}

关于ios - 在 Swift 中覆盖 UIScrollView 的委托(delegate)属性(就像 UICollectionView 一样),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25724709/

相关文章:

ios - SugarWod (iOS) 是否实现了自定义网址?

ios - swift 2 中的 XML 解析器在设备上返回 false

ios - Swift:调用中的额外参数 "progressblock"

ios - 带有自定义标题的 UICollectionView

ios - 登录后图形请求返回nil

html - Iphone 6 或 Ios 8 safari 图像随机重复问题

ios - cordova 3.4.0 使用 paypal 插件

objective-c - swift 3 - 方法不会覆盖其父类(super class)中的任何方法

ios - 动态调整 UICollectionView 大小以确保没有项目间间距

ios - 在 UICollectionView 的两个方向上无限滚动,带有部分