iosswiftuitableviewuibuttontouchescancelled

Touches should cancel function for UITableView is not called


I have a table view that has a UIImage and some UIButton objects in each TableView cell. When I scroll the table view, it works quite well overall. However, if I touch one of the UIButton items to scroll the table view, the UIButton seems to steal the touches and the table view does not scroll. Instead the UIButton items appears to be selected instead. I would like to be able to scroll the table view even when the user touches buttons when starting to scroll. So, I searched for solutions here, tried the following.

extension UITableView {

    override public func touchesShouldCancel(in view: UIView) -> Bool {

        print("the touchesShouldCancel function is called.")

        if view is UIButton {
            return true
        }

        return super.touchesShouldCancel(in: view)
    }

}

However, it doesn't work. The function does not even get called whenever I scroll the table view. What am I missing here? I would greatly appreciate your input. Thanks all.


Solution

  • Subclass UITableView Set tableView canCancelContentTouches to true as per Apple docs

    The scroll view does not call this method if the value of the canCancelContentTouches property is false

    class YourTableView:UITableView {
    
        override func awakeFromNib() {
            canCancelContentTouches = true
            delaysContentTouches = false
        }
    
        override func touchesShouldCancel(in view: UIView) -> Bool {
            
        }
    }