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 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; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With