本文介绍了在Swift中覆盖UIScrollView的委托属性(比如UICollectionView)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

UIScrollView有一个委托属性,符合UIScrollViewDelegate

UIScrollView has a delegate property which conforms to UIScrollViewDelegate

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

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

UICollectionView overrides this property with a different type UICollectionViewDelegate

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

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

当我尝试覆盖UIScrollViews委托时使用我的协议如下:

When I try to override UIScrollViews delegate with my protocol like so:

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

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

}

编译器给了我两个警告:

the compiler gives me two warnings:


  • 类型为MyScrollViewDelegate?的属性委托无法覆盖类型为UIScrollViewDelegate?的属性。

  • '无主'不能应用于非类类型'MyScrollViewDelegate?'

我如何子类化UIScrollView并覆盖委托属性的类型(即使用一个自定义委托协议)?

How can I subclass UIScrollView and override type of delegate property (i.e. use a custom delegate protocol) ?

推荐答案

我认为重写一个继承的属性是Objective-C中可能的但不是(至少目前)在斯威夫特。我处理这个的方法是声明一个单独的委托作为正确类型的计算属性,获取并设置实际委托:

I think overriding an inherited property is something that's possible in Objective-C but not (at least currently) in Swift. The way I've handled this is to declare a separate delegate as a computed property of the correct type that gets and sets the actual 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 }
    }
}

这样调用滚动视图委托的任何东西通常都可以工作,你可以在 self.myDelegate 上调用你的特定委托方法,如下所示:

This way anything that calls the scroll view delegate normally still works, and you can call your particular delegate methods on self.myDelegate, like this:

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

这篇关于在Swift中覆盖UIScrollView的委托属性(比如UICollectionView)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:47