Trouble applying gesture recognizer to navigationbar

与世无争的帅哥 提交于 2019-12-10 17:33:29

问题


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.


回答1:


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.

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




回答2:


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

[self.navigationController.view addGestureRecognizer:oneFingerTwoTaps];


来源:https://stackoverflow.com/questions/11167188/trouble-applying-gesture-recognizer-to-navigationbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!