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/