Method 1:
How about adding a TapGestureRecogniser
on your UINavigationBar
? This will only work if you dont have any buttons on your navigationBar.
//Create a tap gesture with the method to call when tap gesture has been detected
UITapGestureRecognizer* tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(navBarClicked):];
//isolate tap to only the navigation bar
[self.navigationController.navigationBar addGestureRecognizer:tapRecognizer];
//same method name used when setting the tapGesure's selector
-(void)navBarClicked:(UIGestureRecognizer*)recognizer{
//add code to scroll your tableView to the top.
}
and that's about it really.
Some people have found that their back button stops working when adding a tap gesture to the navigation bar, so you can do one of two things:
- Method 2: Set the user interaction enabled to yes and set the tap gesture recogniser like shown in method 2 in detail.
- Method 3: Use a
UIGestureRecognizerDelegate
method calledgestureRecognizer:shouldReceiveTouch
and make it returnNO
when the touch's view is a button, otherwise returnYES
. See method 3 in detail.
Method 2 from point 1: - feels dirty/hackish
[[self.navigationController.navigationBar.subviews objectAtIndex:1] setUserInteractionEnabled:YES];
[[self.navigationController.navigationBar.subviews objectAtIndex:1] addGestureRecognizer:tapRecognizer];
Method 3 from point 2: - a lot better, the right way
implement the UIGestureRecognizerDelegate
protocol in your .h
file, and in your .m
file add the following:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
// Disallow recognition of tap gestures when a navigation Item is tapped
if ((touch.view == backbutton)) {//your back button/left button/whatever buttons you have
return NO;
}
return YES;
}