tabBar:didSelectItem和popToRootViewControllerAnimated

时间:2015-02-04 12:23:49

标签: objective-c iphone xcode uinavigationcontroller uitabbarcontroller

我有一个UITabBarController,其中包含多个UINavigationController&#39}。当您单击标签栏项目时,我希望它将用户导航回该导航控制器的根视图控制器。我有以下代码,适用于iPad2,iPhone4,iPhone5s,但不适用于iPhone5。有没有人知道为什么会这样?

更新:如果我将afterDelay更改为.8,那么它会起作用,但会在更改视图时创建一个闪光灯 - 不太理想!

@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

更新:以下工作代码:

@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

1 个答案:

答案 0 :(得分:1)

您可以通过这样做来避免闪烁,

每次从选项卡A导航到选项卡B,在调用

之后
[self.tabBarController setSelectedIndex:<index of tab>];
在tabBar上

,在标签A上调用popToRootViewControllerAnimated:

这样一旦你导航回选项卡A,你就不必将它弹出到根视图控制器它已经在根目录。

如果您没有按代码更改标签,那么您可以注册以从UITabBarControllerDelegate

获取委托方法

你可以实现

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

获取有关按下viewController的通知