简体   繁体   English

TapGestureRecognizer不会忽略对UIBarButtonItem的点击

[英]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. 我有一个带有UIToolbar的视图,其中包含一些UIBarButtonItems和一个包含一些UITextField的UITableView。

I would like to dismiss the keyboard for a textfield with a tap anywhere. 我想在任何地方轻按以关闭文本字段的键盘。 Therefore I added a TapGestureRecognizer to the view. 因此,我在视图中添加了TapGestureRecognizer。 To avoid that the TapgestureRecognizer handles taps on the UIBarButtonItems I added the following method (delegate is set). 为了避免TapgestureRecognizer处理UIBarButtonItems上的轻击,我添加了以下方法(设置了委托)。

- (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. UIBarButtonItem本身不是视图,但是它具有UIToolbar作为其超级视图。 When I use the above method, the check for isKindOfClass:[UIToolbar class] does not seem to work for all taps on the toolbar. 当我使用上述方法时,isKindOfClass:[UIToolbar class]的检查似乎不适用于工具栏上的所有轻按。 However the check for the superview with isMemberOfClass:[UIToolbar class] works. 但是,使用isMemberOfClass:[UIToolbar class]检查超级视图是可行的。

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. 只需确保在适当的时间启用和禁用手势即可,以免阻止常规的表格操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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