UITabBarController and switching to another tab programmatically
After a user logs in on my app, I then construct some view controllers and a UITabBarController that is then persistent through the rest of my app. Here is the code for that:
.......
//construction of view controllers, standard
NSMutableArray *topLevelControllers = [[[NSMutableArray alloc] init] autorelease];
[topLevelControllers addObject: paymentNavController];
[topLevelControllers addObject: customerNavController];
[topLevelControllers addObject: historyNavController];
UITabBarController *tabBarController = [[[UITabBarController alloc] init] autorelease];
tabBarController.delegate = self;
[tabBarController setViewControllers:topLevelControllers animated:NO];
tabBarController.selectedIndex = 1;
So then lets say in my customerNavController I have a tabl开发者_开发技巧e view and I want to switch the user over to the paymentNavController, switching the selected index of the tabBarController as well.
So how can I, from one of the view controllers it contains, access that UITabBarController?
I ended up using a static method and storing the tab bar globally so I could access it later. This is declared in a file called "LoginViewController"
static id gGlobalInstanceTabBar = nil;
+ (UITabBarController *) tabBarController
{
if (!gGlobalInstanceTabBar)
{
gGlobalInstanceTabBar = [[UITabBarController alloc] init];
}
return gGlobalInstanceTabBar;
}
Then after initializing my navigation controllers, I access the tab bar controller like this and configure it:
UITabBarController *tabBarController = [LoginViewController tabBarController];
Then I can access it anywhere and switch views on it programmatically:
UITabBarController *tabBar = [LoginViewController tabBarController];
//do anything with view controllers, pass values etc here before switching views
[tabBar setSelectedIndex:1];
Any controller (however deep in the hierarchy it may be) that has a parent/ancestor UITabBarController can access it via [self tabBarController]
.
The same works for UINavigationController with the property navigationController
.
I'm assuming you have an AppDelegate, correct? If so, you have code like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self.window addSubview:tabBarController.view];
[self.window makeKeyAndVisible];
return YES;
}
Then, in your logic, use
[self.delegate ...]
To work across the different controllers. Read details here: View Controller Programming
精彩评论