How to remember last selected tab in UITabBarController?

前端 未结 6 1624
小鲜肉
小鲜肉 2021-02-08 04:30

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 functiona

6条回答
  •  独厮守ぢ
    2021-02-08 04:49

    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;
    } 
    

提交回复
热议问题