Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 982
Jonathan Sutherland Avatar asked Mar 13 '14 22:03

Jonathan Sutherland


2 Answers

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 UICollectionView.

- (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; } 
like image 179
DrummerB Avatar answered Sep 23 '22 20:09

DrummerB


SWIFT 3

Here goes..

First implement the UITabBarControllerDelegate in the class and make sure the delegate is set in viewDidLoad

class DesignStoryStreamVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITabBarControllerDelegate {   @IBOutlet weak var collectionView: UICollectionView!   override func viewDidLoad() {         super.viewDidLoad()          self.tabBarController?.delegate = self          collectionView.delegate = self         collectionView.dataSource = self     } } 

Next, put this delegate function somewhere in your class.

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {      let tabBarIndex = tabBarController.selectedIndex      print(tabBarIndex)      if tabBarIndex == 0 {         self.collectionView.setContentOffset(CGPoint.zero, animated: true)     } } 

Make sure to select the correct index in the "if" statement. I included the print function so you can double check.

like image 41
jsanabria Avatar answered Sep 21 '22 20:09

jsanabria