iOS - go to second uiviewcontroller of some tab fr

2019-07-26 09:15发布

问题:

I'm developing an iOS 5 app using Storyboard.

I have UITabBarController which has 3 tabs. Every tab has its own UINavigationController. UINavigationController of first tab has one UITableViewController which segues to another UIViewController etc. UINavigationController of second tab has only one UIViewController.

What I want to achieve is to navigate to UIViewController (second view in UINavigationController of first tab) when certain action happens in UIViewController of second tab.

I've tried to accomplish this using push segue but then the navigation stack becomes mixed with view controllers of different tabs (the back button in destination view controller points to view controller of another tab).

So I want to know what is the "correct way" to accomplish this kind of transition between view controllers of different tabs.

Any help would be very appreciated.

回答1:

You can't use notifications as the first viewController of the first tab might not even be loaded.

So one way you could do it is save a preference (nsuserdefaults perhaps), then switch the tab to the first one, and in the first viewController of the first tab check this preference in viewDidAppear or viewWillAppear, and if it's set then reset the preference (for next time) and auto navigate (push) to the second viewController.

BOOL shouldAutoPush=YES;
[[NSUserDefaults standardUserDefaults] shouldAutoPush forKey:@"shouldAutoPush"];
[[NSUserDefaults standardUserDefaults] synchronize]; 
[self.tabBarController setSelectedIndex:0];

-(void)viewWillAppear:(BOOL)animated {
     if ( [[NSUserDefaults standardUserDefaults] objectForKey:@"shouldAutoPush"] ) {
        BOOL shouldAutoPush=NO;
        [[NSUserDefaults standardUserDefaults] shouldAutoPush forKey:@"shouldAutoPush"];
        [[NSUserDefaults standardUserDefaults] synchronize]; 
        [self.navigationController pushViewController:secondViewController animated:YES];                
     }
}