如何记住 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
更新
目标 C
Swift 3.2
UPDATE
Objective C
Swift 3.2
在 UITabBar 的 Delegate 中,覆盖
item 的索引并将其存储在 NSUserDefaults 中。下次您的应用程序启动时,从那里读取它,并将其设置回选中状态。像这样的事情:
-首先,您将为 UITabBar 设置一个委托,如下所示:
-在 anObject 中,覆盖 didSelectItem:
请注意,您保存了一个 NSNumber,如 int 值不能直接序列化。
当您再次启动应用程序时,它将读取并设置默认值中的 selectedIndex 值:
In the UITabBar's Delegate, overwrite
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:
-in anObject, overwrite didSelectItem:
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:
我对 TabBarController 进行了子类化并:
I subclassed TabBarController and:
我是这样做的。
这两个方法都在 appDelegate 中,tabBarController 是一个实例变量。
Here's how I did it.
Both Methods are in the appDelegate and tabBarController is an instance variable.
这是 Swift 3 的解决方案。只需在情节提要中将 TabBarController 的类设置为
RememberingTabBarController
Here is the Swift 3 solution. Just set the class of your TabBarController to
RememberingTabBarController
in the Storyboard每次用户选择新选项卡时,将所选选项卡索引存储在 NSUserDefaults 首选项中。然后,当应用程序重新启动时,从首选项加载该值并手动选择该选项卡。
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.