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

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


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


You can do like this:

protocol ExtendedUIScrollViewDelegate: UIScrollViewDelegate {    func someNewFunction()}class CustomScrollView: UIScrollView {    weak var myDelegate: ExtendedScrollViewDelegate?    override weak var delegate: UIScrollViewDelegate? {        didSet {            myDelegate = delegate as? ExtendedScrollViewDelegate        }    }}

Hope this helps


My favoured method personally is not to subclass scrollviews directly but to make a UIView subclass containing and acting as delegate for a separate scrollview, then forward that scrollview's delegate messages on to the UIView subclass's own delegate where necessary. This also allows for the adding of custom controls outside of the area defined by the scroll view. It may seem a little inelegant compared to a direct subclass, but it does at least avoid unpleasant hacks.