Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to top in UITableView when the current Tab Bar is tapped again?

I'm trying to replicate the App Store search functionality where tapping the Search Tab Bar again, scrolls the search results back to the first.

My case is simpler in that it's a traditional table view so it needs to scroll to top. I have the UITabBarControllerDelegate set and can detect the tab bar selection.

In the didSelectViewController, I've tried:

- (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
  if(viewController == tabBarController.selectedViewController) {
    [searchResultsTable setContentOffset:CGPointZero animated:YES];
  }
}

and

[searchResultsTable scrollRectToVisible:tableOrigin animated:YES];

where tableOrigin is the table view frame rect that I set in viewDidLoad.

The first implementation (setContentOffset) scrolls up but stops short of the search bar and cuts off the first row partially. I'm assuming this is related to iOS 7 in how the nav bar works?

The second implementation (scrollRectToVisible) works the first time but gets wonky if I come back to the search tab later on.

Is there a reliable, repeatable view to mimic the "scroll to top" functionality the way it works on tapping the Status Bar programmatically and doesn't cut off any rows or Search Bar in iOS 7?

UPDATE: The SearchBar is part of the UITableView.

like image 411
Tree Hugger Avatar asked Jan 20 '26 01:01

Tree Hugger


1 Answers

You can try:

[searchResultsTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 
                                                              inSection:0]
                          atScrollPosition:UITableViewScrollPositionTop
                                  animated:YES];
like image 114
danypata Avatar answered Jan 22 '26 17:01

danypata