Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble applying gesture recognizer to navigationbar

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.

like image 318
Shantanu Avatar asked Dec 16 '22 22:12

Shantanu


2 Answers

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

[self.navigationController.view addGestureRecognizer:oneFingerTwoTaps];
like image 93
Peter Carnesciali Avatar answered Dec 18 '22 12:12

Peter Carnesciali


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

like image 42
fatuous.logic Avatar answered Dec 18 '22 11:12

fatuous.logic