My view has a toolbar with two buttons of type UIBarButtonItem
. I'm trying to implement a gesture recognizer such that when I tap anywhere in the view except in the toolbar, I call a selector. Tapping on a bar button item in the toolbar should call that button's action method. The view conforms to the UIGestureRecognizerDelegate
protocol and implements the shouldReceiveTouch
method as follows:
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldReceiveTouch:(UITouch *) touch {
// Disallow recognition of tap gestures in the toolbar
if ((touch.view == self.sideOneBarButton.customView) &&
(gestureRecognizer == self.tapRecognizer)) {
return NO;
}
return YES;
}
The problem is, when I tap on the toolbar button, touch.view
is of type UTToolbarTextButton*
which is an undocumented class, so my if statement fails and the shouldReceiveTouch
always returns YES and my button e开发者_运维问答vent never gets called.
Ideally, I'd like to say: if the touch is anywhere in the toolbar, then return no. What's the best way to do this?
About the delegate function, this is good for me.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if ([touch.view.superview isKindOfClass:[UIToolbar class]]) {
return NO;
}
return YES;
}
There is a way to ignore the gesture on anything that isn't your central view.
For instance I have:
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(dismissKeyboard)];
tap.delegate = self;
[self.view addGestureRecognizer:tap];
Add the gesture delegate to the class:
@interface myClass : UIViewController<..,UIGestureRecognizerDelegate,..>
and now the delegate function:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if (touch.view == self.view)
{
return YES;
}
return NO;
}
This has worked out for me when I couldn't use the UIToolbar because of the gesture
Also, as @LandedGently has mentioned, there is more information here:
UIButton inside a view that has a UITapGestureRecognizer
so people don't miss the link in the comments.
精彩评论