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

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

UIScrollView has a delegate property which conforms to UIScrollViewDelegate

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


        
6条回答
  •  眼角桃花
    2021-02-01 02:55

    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 }
        }
    }
    

    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() {
        // ...
    }
    

提交回复
热议问题