Overriding delegate property of UIScrollView in Swift (like UICollectionView does)

后端 未结 6 2063
春和景丽
春和景丽 2021-02-01 02:36

UIScrollView has a delegate property which conforms to UIScrollViewDelegate

protocol UIScrollViewDelegate : NSObjectProtocol {
    //...
}
class UIScrollView : U         


        
6条回答
  •  有刺的猬
    2021-02-01 03:03

    Here is a solution for changing the type of the overriding properties in Swift. It is especially useful when you need to extend protocols of delegates.

    @objc protocol ExtendedUIScrollViewDelegate: UIScrollViewDelegate {
         func someNewFunction()
    }
    
    class CustomScrollView: UIScrollView {
    
        weak var delegateInterceptor: ExtendedScrollViewDelegate?
        override var delegate: UIScrollViewDelegate! {
            didSet {
                if let newValue = delegate {
                    let castedDelegate = unsafeBitCast(delegate, ExtendedScrollViewDelegate.self)
                    delegateInterceptor = castedDelegate
                }
                else {
                    delegateInterceptor = nil
                }
            }
        }
    }
    

    This works as tested with Swift version 1.2. I hope it helps.

提交回复
热议问题