Can somebody please tell me how I can determine which tabbar index a view controll开发者_运维百科er is at.
to simplify - I can jump to a tabBarItem at the moment by hardcoding its index.
self.tabBarController.selectedIndex = 3;
However, should the user customize the tab bar items, there is a possibility the viewController at number 3 isn't the one that the user will want as it has been moved. How can I determine where it has moved to so I can select the correct one.
Any help please.
Thanks,
Lee
Use the self.tabBarController.selectedViewController
property.
UPDATE: To get the index of a specific viewController, use:
NSUInteger index = [self.tabBarController.viewControllers indexOfObjectIdenticalTo:specificViewController];
You can get the list of controllers in the UITabBar and compare by pointer value. For example, a view controller that is in a UITabBar can figure out it's location like this:
int loc = 0;
for (UIViewController *vc in [self.tabBarController viewControllers]){
if (vc == self.navigationController || vc == self){
break;
}
loc++;
}
if (loc == [[self.tabBarController viewControllers] count])
NSLog(@"Could not find me!");
else
NSLog(@"Im in tab:% d",loc);
ok, so I had no luck with any of any of the answers successfully - but I did sort it so thought I would explain how I did it incase there is someone else who gets stuck attempting to do what I did.
each tabBarItem on my tab bar controller was assigned a tag that started with 0 and say ended with 8. (can be done in IB also)
make sure delegate for tabBarController etc is all set and inplement the following delegate method:
- (void)tabBarController:(UITabBarController *)theTabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed {
NSInteger count = self.tabBarController.viewControllers.count;
NSMutableArray *tabOrderArray = [[NSMutableArray alloc] initWithCapacity:count];
for (UINavigationController *viewController in viewControllers)
{
NSInteger tag = viewController.tabBarItem.tag;
[tabOrderArray addObject:[NSNumber numberWithInteger:tag]];
}
[prefs setObject:tabOrderArray forKey:@"tabOrder"];
[prefs synchronize]; // optional
[tabOrderArray release];
}
(note i use navControllers ontop of ViewControllers in my app hence that for loop)
so now what i was able to do was simply do a check if there was an array in prefs with a new tab bar order
NSArray * tabBarOrder = [prefs objectForKey:@"tabOrder"];
if(tabBarOrder) { ... }
if there was a tab bar order i could get index of the VC i wanted with '[tabBarOrder indexOfObjectIdenticalTo:[NSNumber numberWithInt:theViewsTagImAfter]];
and if there was no array in prefs you can safely assume it hasn't moved and is where is.
**
Any one feel free to destroy how I have done this should you feel you could have accomplished this in a sleeker way. however, this works and the other suggestions didnt.
精彩评论