简体   繁体   中英

iOS: Prevent tapping through a disabled toolbar button

I'm working with iOS SDK 6 and 7. I have a UIToolbar that overlays another view—call it "View B"—that has touches* message handlers for dealing with taps. The toolbar is, of course, full of UIBarButtonItems. When a toolbar button item is enabled, then when I tap it or drag it, View B receives no touch messages, and this is the desired effect. But when a button item is disabled, tapping or dragging it sends a message down "through" the toolbar (as it were) to View B underneath.

How do I ensure that taps over a toolbar are not passed down to underlying views, even when the taps occur over disabled bar button items?

I still find this a rather unintuitive behavior, but a workaround is fairly easy. The touchesBegan event, for example, passes a touches NSSet that one normally uses to consider what touches to handle. The problem here is that the underlying view will receive the set of touches that includes touches that don't belong to it and that it should not handle. Therefore, rather than:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (UITouch* touch in touches)
    {
        ...
    }
}

...use...

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSSet* myTouches = [event touchesForView: self];

    for (UITouch* touch in myTouches)
    {
        ...
    }
}

...thus ignoring the SDK-provided touches and using only the touches relevant to "View B" itself.

If you are already handling touch events manually in View B, just check if the tapped point for the touch event is inside the frame of the disabled button. If so, just ignore it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM