popToRootViewController with animation and then sw

2019-08-08 00:21发布

问题:

I have a UITabBarController with 4 views/tabs. Each view is a UINavigationController.

How can I popToRootViewController on one of these UINavigationControllers then switch tabs and push a viewController onto another UINavigationController using animation throughout?

So the sequence would be:

At start we are in Tab 1's view which is a UINavigationController. A View has been pushed onto it beyond its root ViewController.

-Tab 1
   - UINavigationController1
      - RootViewController1
      - SomeViewController1 [We are here]

-Tab 2
   - UINavigationController2
      - RootViewController2

A button is tapped in SomeViewController1 that causes the following:

  1. UINavigationController1 pops to its root view controller (with animation)
  2. UITabBarController switches tab to Tab2
  3. SomeViewController2 is pushed onto UINavigationController2 (with animation)

So the view looks like this:

-Tab 1
   - UINavigationController1
      - RootViewController1

-Tab 2
   - UINavigationController2
      - RootViewController2
      - SomeViewController2 [We are here]

回答1:

int tabYouWantToSelect=2;
BOOL isNavigation=YES;
[[self.tabBarController selectedViewController].navigationController popToRootViewControllerAnimated:YES];

//if any controller is presented as a model view then
//[[self.tabBarController selectedViewController] dismissModalViewControllerAnimated:YES];

[self.tabBarController setSelectedIndex:tabYouWantToSelect];

//the newly pushed view controller's viewWillAppear
-(void)viewWillAppear:(BOOL)animated {
        if(isNavigation){
            [self.navigationController pushViewController:objAddLocation animated:YES];                
         }
}


回答2:

  1. Pop to rootview controller on the navigation controller you are currently showing in your UITabBar Controller
  2. Change the tab programmatically
  3. Push the viewController on the new tab's navigationController programmatically

All this should happen through your applications delegate implementation file.

If you need the code as well let me know...



回答3:

Here is how I've done it. I feel it is much cleaner than infecting the root VC with code that isn't relevant to it.

I created a UINaviationControllerDelegate that checks the number of UIViewControllers left on its UINavigationController. If there is only one left it posts a stackAtRoot notification. Meanwhile just before I popToRootViewController I register a Command that is triggered by this notification. When it is triggered I have it orchestrate the tab switch and pushing of a VC onto the new tab's UINavigationController. It immediately unregisters the command, so it will not be called again unless reregistered.