Switching to another View with UITabBar
I just started developing with the iPhone SDK and I have a problem with switching to another tab with the UITabBar.
This is my current code, and it works so far:
myAppAppDelegate *appDel = (myAppAppDelegate *)[[UIAppl开发者_Go百科ication sharedApplication] delegate]
[appDel.tabBar setSelectedViewController:[appDel.tabBar.viewControllers objectAtIndex:5]];
But if i go to the more tab and rearrange the tabbar items, the index of the viewControllers change too. Is there any possibility how I could solve this problem?
First of all, if you ever find yourself typing this:
(myAppAppDelegate *)[[UIApplication sharedApplication] delegate]
You can probably benefit from a better design. This code probably comes from a view controller, in which case you are calling out to the App delegate from a view controller, and dealing with stuff you shouldn't have knowledge of (the tab bar).
A better design is to delegate out to the app delegate, and the app delegate switches the tab for you. The app delegate should have references to the actual view controllers in the tab bar (you can hook these up via IB if not) so you can call setSelectedViewController:
with the correct object, rather than indexing into the tab bar's array:
/* Somewhere in the app delegate */
- (void)selectFooBarController {
[self.tabBar setSelectedViewController:self.fooBarController];
}
Now if you don't want to bother with delegation you can just put a method on the app delegate (like the one above) and your original code becomes:
myAppAppDelegate *appDel = (myAppAppDelegate *)[[UIApplication sharedApplication] delegate]
[appDel selectFooBarController];
Again you will need to add IBOutlet properties to your app delegate which you connect to the fooBarController etc. in Interface Builder. This will let you directly reference them rather than grabbing them out of an array.
The most straight forward means I can think off relies on the fact that when you application first starts, unless you are doing something to save the re-ordering, you could save off the initial list of UIViewControllers:
initialOrdering = [[appDel.tabBar viewControllers] copy];
Where 'initialOrdering' is an NSArray* which you would then use instead of appDel.tabBar.viewControllers in the code you posted.
精彩评论