Click events in UINavigationBar overridden by the gesture recognizer

Octoshape picture Octoshape · Oct 14, 2011 · Viewed 9.2k times · Source

The question in the first place was:

When you have a tableView how to implement that the user can tap the NavigationBar to scroll all the way to the top.

Solution:

- (void)viewDidLoad {
    UITapGestureRecognizer* tapRecon = [[UITapGestureRecognizer alloc]
              initWithTarget:self action:@selector(navigationBarDoubleTap:)];
    tapRecon.numberOfTapsRequired = 2;
    [navController.navigationBar addGestureRecognizer:tapRecon];
    [tapRecon release];
}

- (void)navigationBarDoubleTap:(UIGestureRecognizer*)recognizer {
    [tableView setContentOffset:CGPointMake(0,0) animated:YES];
}

Which works like a charm!

But Drarok pointed out an issue:

This approach is only viable if you don't have a back button, or rightBarButtonItem. Their click events are overridden by the gesture recognizer

My question:

How can I have the nice feature that my NavigationBar is clickable but still be able to use the back buttons in my app?

So either find a different solution that doesn't override the back button or find a solution to get the back button back to working again :)

Answer

Ben Flynn picture Ben Flynn · Apr 9, 2012

Rather than using location view, I solved this by checking the class of the UITouch.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return (![[[touch view] class] isSubclassOfClass:[UIControl class]]);
}

Note that the nav buttons are of type UINavigationButton which is not exposed, hence the subclass checking.

This method goes in the class you designate as the delegate of the gesture recognizer. If you're just getting started with gesture recognizers, note that the delegate is set separately from the target.