Jonathan Sutherland Jonathan Sutherland - 4 months ago 115
iOS Question

Tap tab bar to scroll to top of UITableViewController

Tapping the tab bar icon for the current navigation controller already returns the user to the root view, but if they are scrolled way down, if they tap it again I want it to scroll to the top (same effect as tapping the status bar). How would I do this?

A good example is Instagram's feed, scroll down then tap the home icon in the tab bar to scroll back to top.

The scrolling back to the top is easy, but connecting it to the tab bar controller is what I'm stuck on.


Implement the UITabBarControllerDelegate method tabBarController:didSelectViewController: to be notified when the user selects a tab. This method is also called when the same tab button is tapped again, even if that tab is already selected.

A good place to implement this delegate would probably be your AppDelegate. Or the object that logically "owns" the tab bar controller.

I would declare and implement a method that can be called on your view controllers to scroll the collection view.

- (void)tabBarController:(UITabBarController *)tabBarController 
 didSelectViewController:(UIViewController *)viewController
    static UIViewController *previousController = nil;
    if (previousController == viewController) {
        // the same tab was tapped a second time
        if ([viewController respondsToSelector:@selector(scrollToTop)]) {
            [viewController scrollToTop];
    previousController = viewController;