如何记住UITabBarController中最后选择的选项卡?

编程入门 行业动态 更新时间:2024-10-25 14:29:05
本文介绍了如何记住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中最后选择的选项卡?

本文发布于:2023-11-25 02:04:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627873.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:选项卡   UITabBarController

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!