简体   繁体   中英

Tap on UIBarButtonItem is not ignored by TapGestureRecognizer

I have a view with a UIToolbar with a few UIBarButtonItems and a UITableView containing some UITextFields.

I would like to dismiss the keyboard for a textfield with a tap anywhere. Therefore I added a TapGestureRecognizer to the view. To avoid that the TapgestureRecognizer handles taps on the UIBarButtonItems I added the following method (delegate is set).

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    UIView *view = touch.view;
    while (view) {
         NSLog(@"Class of view: %@", NSStringFromClass([view class]));
         view = view.superview;
    }

    // Disallow recognition of tap gestures in the toolbar
    if ([touch.view isKindOfClass:[UIToolbar class]]) {
        return NO;
    }

    if ([touch.view.superview isMemberOfClass:[UIToolbar class]]) {
         return NO;
    }

    return YES;
}

A UIBarButtonItem is not a view itself, but it has UIToolbar as its superview. When I use the above method, the check for isKindOfClass:[UIToolbar class] does not seem to work for all taps on the toolbar. However the check for the superview with isMemberOfClass:[UIToolbar class] works.

I don't understand this. Maybe someone can explain this behavior?

You shouldn't rely on the view hierarchy around private view classes. It could change at any time.

A better approach is to add the gesture to the table view (or other appropriate view which represents the area you're interested in). Just be sure to enable and disable the gesture at appropriate times so as not to block the usual table operation.

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