如何记住UITabBarController中最后选择的选项卡? [英] How to remember last selected tab in UITabBarController?

查看:131
本文介绍了如何记住UITabBarController中最后选择的选项卡?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让我的应用记住在应用退出之前最后一次查看哪个标签,以便应用在下次启动时打开到相同的标签。这是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中最后选择的选项卡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆