Question

I have a UIView with a UINavigationBar, a UITabBar and a UITableView. When i press the status bar the UITableView scrolls to top because i have it set to TRUE.

I want to be able to do the same, by pressing the UINavigationBar like it happens in some apps. Setting the UITableView to scrollsToTop = TRUE only works if the user presses the StatusBar.

Was it helpful?

Solution

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:

  1. Method 2: Set the user interaction enabled to yes and set the tap gesture recogniser like shown in method 2 in detail.
  2. Method 3: Use a UIGestureRecognizerDelegate method called gestureRecognizer:shouldReceiveTouch and make it return NO when the touch's view is a button, otherwise return YES. 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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top