Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...