Programmatically switch to another tab AND switch to the first view controller?

后端 未结 3 1055
无人共我
无人共我 2020-12-22 12:28

How do I programmatically switch to another tab and go to the first view in the navigation stack ?

I can switch to a different tab.

self.tabBarContro         


        
相关标签:
3条回答
  • 2020-12-22 13:01

    Assuming the rootViewController for the tab bar controller is a navigation controller, get a reference to it then pop to the view controller you want. You can even do this BEFORE you switch the tab.

    EDIT: I keep forgetting I subclassed UINavigationController to prevent the default behavior of the tab bar controller telling the navigation controller to pop to its rootViewController when the tab is switched (this is the behavior when a person taps on a tab, not sure if it happens when its done programmatically.) This is the code I use:

    - (NSArray *)popToRootViewControllerAnimated:(BOOL)animated
    {
        //NSLog(@"popToRootViewControllerAnimated");
    
        return @[];
    }
    
    0 讨论(0)
  • 2020-12-22 13:08

    Know this is an old one, but I was faced with a similar problem. I have 3 tabs in a tabViewController, each tab has a Navigation tree that can be drilled through. When a user switches tab, I need the rootviewcontroller of that tab presented. My solution was to add the following lines to those view controllers in the Navigation trees:

        -(void)viewWillDisappear:(BOOL)animated
        {
           [super viewWillDisappear:YES];
            DLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
           [self.tabBarController.viewControllers[self.tabBarController.selectedIndex] popToRootViewControllerAnimated:YES];
    
         }
    

    If the user is in any of the views with the above code and switches tabs, the tab they left is popped to the root view, so when they come back everything is cool....

    0 讨论(0)
  • 2020-12-22 13:13

    I assume you have UINavigationControllers in your UITabBarController. If that's the case you can use popToRootViewControllerAnimated: to go to the first view controller.

    int index = 4;
    self.tabBarController.selectedIndex = index;
    [self.tabBarController.viewControllers[index] popToRootViewControllerAnimated:NO];
    
    0 讨论(0)
提交回复
热议问题