Objective-c – Prevent disabled UIButton from propagating touch events

cocoa-touchevent handlingiphoneobjective cuibutton

My application has two overlapping UIButtons. The top button may be disabled at times. However, in this case any touch events it receives seem to be passed down to the underlying view, which in my case is the other button.

What I need is the top button intercepting all touches and preventing them from reaching the bottom button, even in disabled state (I would be happy even if it's designated action is invoked in the disabled state).

So far I've tried:

[topButton setUserInteractionEnabled:YES];

and

[topButton setExclusiveTouch:YES];

though the later case is probably undesirable since I still need the bottom button responding to events if it's the first view clicked. Either way none of them work.

Best Answer

I added the following method to superview of the disabled button:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if (!self.watchButton.enabled &&
        [self.watchButton pointInside:[self convertPoint:point toView:self.watchButton]
                            withEvent:nil]) {
        return nil;
    }
    return [super hitTest:point withEvent:event];
}

This works well with UITableView cells.

Related Topic