简体   繁体   中英

tabBar:didSelectItem and popToRootViewControllerAnimated

I have a UITabBarController which contains several UINavigationController 's. When you click on a tab bar item I would like for it to navigation the user back to the root view controller for that navigation controller. I have the following code which works perfectly for an iPad2, iPhone4, iPhone5s, but not for an iPhone5. Does anyone have any idea as to why this might be?

Update : If I change the afterDelay to .8 then it will work, but creates a flash as it changes view - not very desirable!

@implementation NavigationTabs

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    // Thanks to http://stackoverflow.com/questions/2336907/how-to-reset-a-uinavigationview-to-display-the-root-controller-when-user-clicks#answer-21544648
    if ([self.selectedViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController * view = (UINavigationController *)self.selectedViewController;
        [view performSelector:@selector(popToRootViewControllerAnimated:) withObject:nil afterDelay:.5];
    }
}

@end

Update : Working code below:

@interface NavigationTabs : UITabBarController <UITabBarControllerDelegate>

@end

@implementation NavigationTabs

- (void)viewDidLoad {
    self.delegate = self;
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        [(UINavigationController *)viewController popToRootViewControllerAnimated:NO];
    }
    return YES;
}

@end

You can avoid the flashing by doing so,

Every time you navigate from tab A to tab B, after you call the

[self.tabBarController setSelectedIndex:<index of tab>];

on tabBar, call the popToRootViewControllerAnimated: on tab A.

That way once you navigate back to Tab A you don't have to pop it to the root viewController it will be at the root already.

If you are not changing the tabs by code, then you can register to get delegate methods from UITabBarControllerDelegate

you can implement the

- (BOOL)tabBarController:(UITabBarController *)tabBarController
shouldSelectViewController:(UIViewController *)viewController

To get notification on what viewController has been pressed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM