Question

I started with the default Tabbed Application, added some tabs in the Storyboards with their own viewcontrollers, how can I know when a tab that's already selected, get's touched again?

Tab 1 goes to a webview that has loaded other pages, when the user hits the home tab again, when it's still highlighted, I'd like to reload the initial url where it started.

Thanks for any ideas!

Was it helpful?

Solution

The UITabBarControllerDelegate method [– tabBarController:didSelectViewController:] gets called each time the tab bar is touched. The documentation for this API states:

In iOS v3.0 and later, this (selected view controller) could be the same view controller that was already selected.

So if you detect your specified tab being selected again, you can have this delegate method reload your initial URL.

OTHER TIPS

@interface AHTabBarController () <UITabBarControllerDelegate>
@property (nonatomic, strong) UIViewController* previousViewController;
@end

///

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    if ([viewController isEqual:self.previousViewController])
    {
          NSLog(@"reselect tabbar");
    }
    self.previousViewController = viewController;
}

Here is a full answer for common use cases.


  1. Create a protocol for handling the reselection

    protocol TabInteractionDelegate {
        func didReselectTab(at index: Int, with item: UITabBarItem)
    }
    
  2. Call the protocol from a Custom UITabBarController

    class CustomTabBarController: UITabBarController, UITabBarControllerDelegate {
    
        var tabInteractionDelegate: TabInteractionDelegate?
    
        // ...
    
        override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    
            // This will:
            // 1. Call when the tab is reselected (i.e. The tab does not switch)
            // 2. NOT get called when the tab is switching to a new tab and showing a new view controller
    
            if (tabBar.items?[selectedIndex] == item) {
                 tabInteractionDelegate?.didReselectTab(at: selectedIndex, with: item)
            }
         }
    
    }
    
  3. Listen to changed in the UIViewController you need it in

    class CustomViewController: UIViewController, TabInteractionDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Attach the delegate 👇
            if let tabBarCont = tabBarController as? ChoiceTabBarController {
                tabBarCont.tabInteractionDelegate = self
            }
    
        }
    
        // Listen to the change 👇
        func didReselectTab(at index: Int, with item: UITabBarItem) {
            print("\(index) :: \(item)")
    
            // Here you can grab your scrollview and scroll to top or something else
        }
    
    }
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top