UIButton continue tracking even when out of bounds

249 Views Asked by At

I'm trying to track the touches on the button. But whenever the touch leaves the button frame, it stops tracking the touch all together.

I've tried using:

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    let relativeFrame = bounds
    let hitTestInsets = UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10)

    return UIEdgeInsetsInsetRect(relativeFrame, hitTestInsets).contains(point)
}

and

override open func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

    let minimalWidthAndHeight: CGFloat = 60

    let buttonSize = frame.size
    let widthToAdd = (minimalWidthAndHeight - buttonSize.width > 0) ? minimalWidthAndHeight - buttonSize.width : 0
    let heightToAdd = (minimalWidthAndHeight - buttonSize.height > 0) ? minimalWidthAndHeight - buttonSize.height : 0
    let largerFrame = CGRect(x: 0-(widthToAdd / 2), y: 0-(heightToAdd / 2), width: buttonSize.width + widthToAdd, height: buttonSize.height + heightToAdd)
    return largerFrame.contains(point) ? self : nil
}

and I also tried using continueTracking(with:) but in all cases, whenever the touch moves away from the button frame, cancelTracking(with:) and touchesCancelled(with:) is called.

What do I have to do to make it keep tracking even when the touch leaves the frame of the button?

0

There are 0 best solutions below