How do I integrate popToRootViewControllerAnimated with my tabs?

北战南征 提交于 2019-12-04 19:30:18

Adam - I ended up ditching the subclass idea even though it worked, as there is a much easier method.

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        [(UINavigationController*)viewController popToRootViewControllerAnimated:YES];
    }
}

This is the code required. I've uploaded this sample project to play around with. The main points are

  • the UITabBarController delegate must be set to the App Delegate.
  • the App Delegate must implement the <UITabBarControllerDelegate> protocol.
  • the App Delegate must implement the code above.

The sample project also shows one way to selectively choose which navigation controllers this occurs with.

Yes this needs to be hardcoded.

If you're using a UITabBarController (I assume you probably are) you'll need to subclass it and override. This will try pop to the root view controller of each navigation controller on a tab. If the root view of a tab item is not a navigation item you will get an exception though.

@interface MyTabBarControllerSubClass : UITabBarController {
}
@end
@implementation MyTabBarControllerSubClass
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    [super tabBar:tabBar didSelectItem:item];
    [(UINavigationController*)self.selectedViewController popToRootViewControllerAnimated:YES];
}
@end

Don't forget to select your subclass in IB :-)

You could also make something a UITabBarControllerDelegate. Though it would probably be harder to implement.

Not sure why, but for me on Xcode 6 with Swift this solution did not work out. It seems even if didSelectViewController is called, popToRootViewControllerAnimated(false) is not.

I found that calling shouldSelectViewController instead works fine for me:

func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
    if viewController.isKindOfClass(UINavigationController) {
        (viewController as UINavigationController).popToRootViewControllerAnimated(false)
        return true
    }
    return true
}

Not sure though if it is a good approach.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!