Klemen Zagar Klemen Zagar - 18 days ago 5
iOS Question

How to override function only on specific object in Swift?

Im getting familiar with Swift.

In obj-c, to add some touch functionality to UIScrollView I subclassed it and put this inside

- (BOOL)touchesShouldCancelInContentView:(UIView *)view {
return YES;
}


But in swift it's recommended to user protocols instead. If I use extensions, then this will become part of every UIScrollView on that view controller. I have two scrollviews on a screen and I want to add this only to one of them. How can I make an extension to only one scrollView?

Answer

Create custom subclass of UIScrollView. and override touchesShouldCancelInContentView there

class YourClass: UIScrollView {

 override func touchesShouldCancelInContentView(view: UIView) -> Bool {

    return false
 }
} 

Or if you want to give same class to both scrollview you can create @IBInspectable property. it is also accessible from the identity inspector.

class MyScrollView: UIScrollView {

 @IBInspectable var touchCanceled: Bool = true

  override func touchesShouldCancelInContentView(view: UIView) -> Bool   {
    return self.touchCanceled
}

}

enter image description here