Trouble applying gesture recognizer to navigationb

2019-06-28 04:38发布

In my iPad Application I have multiple views on a screen.

What I want to do is apply a double tap Gesture Recognizer to the Navigation Bar. But I had no success, however when the same gesture recognizer applied to that view it works.

Here is the code I am using:

// Create gesture recognizer, notice the selector method
UITapGestureRecognizer *oneFingerTwoTaps = 
[[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerTwoTaps)] autorelease];

// Set required taps and number of touches
[oneFingerTwoTaps setNumberOfTapsRequired:2];
[oneFingerTwoTaps setNumberOfTouchesRequired:1];

[self.view addGestureRecognizer:oneFingerTwoTaps];

This works on view, but when this is done:

[self.navigationController.navigationBar addGestureRecognizer:oneFingerTwoTaps]

doesn't work.

2条回答
We Are One
2楼-- · 2019-06-28 05:16

For anyone else viewing this, here is a much simpler way to do this.

[self.navigationController.view addGestureRecognizer:oneFingerTwoTaps];
查看更多
女痞
3楼-- · 2019-06-28 05:28

For this you need to subclass UINavigationBar, override the init button in it and add your gesture recognizer there.

So say you make a subclass called 'CustomNavigationBar' - in your m file you would have an init method like this:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if ((self = [super initWithCoder:aDecoder])) 
    {
        UISwipeGestureRecognizer *swipeRight;
        swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipeRight:)];
        [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
        [swipeRight setNumberOfTouchesRequired:1];
        [swipeRight setEnabled:YES];
        [self addGestureRecognizer:swipeRight];
    }
    return self;
}

Then you need to set the class name of your navigation bar in interface builder to the name of your subclass.

enter image description here

Also it's handy to add a delegate protocol to your navigation bar to listen for methods sent at the end of your gestures. For example - in the case of the above swipe right:

@protocol CustomNavigationbarDelegate <NSObject>
    - (void)customNavBarDidFinishSwipeRight;
@end

then in the m file - on the gesture recognised method (whatever you make it) you can trigger this delegate method.

Hope this helps

查看更多
登录 后发表回答