views:

380

answers:

2

I'm trying to make my app remember which tab was last being viewed before the app quit, so that the app opens up to the same tab when it is next launched. This is the functionality of the iPhone's phone function: how can I do this?

+1  A: 

Store the selected tab index in the NSUserDefaults preferences each time the user selects a new tab. Then when the app starts back up, load that value from the preferences and manually select that tab.

raidfive
+1  A: 

In the UITabBar's Delegate, overwrite

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item

and store item's index in NSUserDefaults. Next time your app starts, read it from there, and set it back to being selected. Something like this:

-first, you would set a delegate for your UITabBar, like this:

tabBarController.delegate = anObject;

-in anObject, overwrite didSelectItem:

       - (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
        {
          NSUserDefaults *def = [NSUserDefaults standardUserDefaults];

          [def setInteger: [NSNumber numberWithInt: tabBarController.selectedIndex]
 forKey:@"activeTab"];

          [def synchronize];
        }

Note that you save a NSNumber, as int values cannot be serialized directly. When you start the app again, it will read and set the selectedIndex value from the defaults:

- (void)applicationDidFinishLaunchingUIApplication *)application {  
   NSUserDefaults *def = [NSUserDefaults standardUserDefaults];

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

   tabBarController.selectedIndex = activeTab;
}
luvieere
@luvieere I'm sorry but can you elaborate with a little more sample code please?
isaaclimdc
Sure, I just did that.
luvieere