我正在尝试让我的应用记住在应用退出之前最后一次查看哪个标签,以便应用在下次启动时打开到相同的标签。这是iPhone手机功能的功能:我该怎么做?
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?
推荐答案在UITabBar的代表中,覆盖
In the UITabBar's Delegate, overwrite
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item并在NSUserDefaults中存储 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:
- 首先,你要为你的UITabBar设置一个委托,如下所示:
-first, you would set a delegate for your UITabBar, like this:
tabBarController.delegate = anObject;-in anObject ,覆盖 didSelectItem :
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item { NSUserDefaults *def = [NSUserDefaults standardUserDefaults]; [def setInteger: [NSNumber numberWithInt: tabBarController.selectedIndex] forKey:@"activeTab"]; [def synchronize]; }请注意,保存NSNumber,如 int 值无法直接序列化。 当您再次启动应用程序时,它将读取并设置默认值中的 selectedIndex 值:
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; }更多推荐
如何记住UITabBarController中最后选择的选项卡?
发布评论