Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

iphone - Programmatically changing the selected tab of tabBarController

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: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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...