Monday, June 10, 2013

UITabBarController selectedIndex example in Objective C (iOS).

UITabBarController selectedIndex

The index of the view controller associated with the currently selected tab item.

@property(nonatomic) NSUInteger selectedIndex

Discussion of [UITabBarController selectedIndex]
This property nominally represents an index into the array of the viewControllers property. However, if the selected view controller is currently the More navigation controller, this property contains the value NSNotFound. Setting this property changes the selected view controller to the one at the designated index in the viewControllers array. To select the More navigation controller itself, you must change the value of the selectedViewController property instead.[UITabBarController selectedIndex]

In versions of iOS prior to version 3.0, this property reflects the index of the selected tab bar item only. Attempting to set this value to an index of a view controller that is not visible in the tab bar, but is instead managed by the More navigation controller, has no effect.

UITabBarController selectedIndex example.
int index = tabBarController.selectedIndex;
if (tabBarController.selectedViewController ==
    tabBarController.moreNavigationController) {
    index = -1;  //assign some placeholder index for the "More" controller

Example of [UITabBarController selectedIndex].
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
          NSUserDefaults *def = [NSUserDefaults standardUserDefaults];

          [def setInteger: [NSNumber numberWithInt: tabBarController.selectedIndex]

          [def synchronize];

UITabBarController selectedIndex example.
- (void)applicationDidFinishLaunchingUIApplication *)application { 
   NSUserDefaults *def = [NSUserDefaults standardUserDefaults];

   int activeTab = [(NSNumber*)[def objectForKey:@"activeTab"] intValue];

   tabBarController.selectedIndex = activeTab;

End of UITabBarController selectedIndex example article.