开发者

Programmatically changing the selected tab of tabBarController

开发者 https://www.devze.com 2023-02-05 13:57 出处:网络
I have a basic project created in xcode as a \"Tab Bar Application\", What I would like is to have the application on load switch to the 2nd tab if BOOL x is true.

I have a basic project created in xcode as a "Tab Bar Application", What I would like is to have the application on load switch to the 2nd tab if BOOL x is true.

Right now I have: (located in FirstViewController.m in viewDidLoad)

if(x){
    [self.tabBarController setSelectedIndex:开发者_Python百科1];
}

This causes the selected tab at the bottom of the page to highlight the 2nd tab, however the view remains that of the first tab.

How would I go about changing the view to that of the 2nd tab?


Well, I reproduced your issue, and solved it by moving the switching logic from -viewDidLoad to -viewDidAppear:. So basically, change:

- (void)viewDidLoad {
    // Other code...
    if(x){
        [self.tabBarController setSelectedIndex:1];
    }
}

to:

- (void)viewDidAppear:(BOOL)animated {
    // Other code...
    if(x){
        [self.tabBarController setSelectedIndex:1];
    }
}

Now, as to why this is the case, I can only guess, without more digging, that it has to do with the order things are initialized. It is possible that your view controller's viewDidLoad is being called before the parent tab bar controller has finished its own initialization. Holding off until your view has actually appeared ensures that everything is loaded and in a consistent state.


Assuming that you are working with a controller that is a subclass of the UITabBarController, you only need to set the selectedIndex property.

For example:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.selectedIndex = 1;
}

I prefer to do this assignment in the viewDidLoad method so you can be guaranteed that only the view controller at the selected index is displayed. If you use the viewDidAppear function, you will occasion see the view controller at index 0 displayed briefly when the tab bar view loads before the one at index 1 is shown.


This would suffice:

[tabBar setSelectedIndex:0];


[self.tabBarController setSelectedIndex:1]
[window addSubview:[tabBarController view]];
[window makeKeyAndVisible];


For Swift 3.0

if(x)
{ 
  self.tabBarController?.selectedIndex = 1
}
0

精彩评论

暂无评论...
验证码 换一张
取 消