Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton handle touch and then pass through?

Is it possible to handle touch happened to UIButton and then pass it underneath to the next responder?

like image 330
Nik Avatar asked Dec 02 '25 11:12

Nik


1 Answers

EDIT

A valid approach is also to override the touchesEnded:withEvent: method of UIResponder

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // handle touch
    [super touchesEnded:touches withEvent:event];
} 

From the documentation:

The default implementation of this method does nothing. However immediate UIKit subclasses of UIResponder, particularly UIView, forward the message up the responder chain. To forward the message to the next responder, send the message to super (the superclass implementation); do not send the message directly to the next responder.


Original answer

In order to determine which UIView in the view hierarchy should receive a touch, the method -[UIView hitTest:withEvent:] is used. As per the documentation:

This method traverses the view hierarchy by calling the pointInside:withEvent: method of each subview to determine which subview should receive a touch event. If pointInside:withEvent: returns YES, then the subview’s hierarchy is similarly traversed until the frontmost view containing the specified point is found. If a view does not contain the point, its branch of the view hierarchy is ignored.

So an approach could be creating a UIButton subclass and override the method -pointInside:withEvent:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    if (CGRectContainsPoint(self.bounds, point) {
        // The touch is within the button's bounds
    }
    return NO;
}

This will give you the opportunity of handling the touch within the button's bounds, but at the same time returning NO will make the hit test fail, passing the touch along in the view hierarchy.

like image 147
Gabriele Petronella Avatar answered Dec 05 '25 02:12

Gabriele Petronella