How to save tab bar order when app is terminated?
The following exam开发者_如何学编程ple: http://www.raddonline.com/blogs/geek-journal/iphone-sdk-uitabbarcontroller-how-to-save-user-customized-tab-order/
Doesn't work in iOS4.
I would like to be able to save the order of my tabs when the application is shut down.
You can set your Application delegate to also be a UITabBarController
delegate, and when the tab is selected, you can record the selection to [NSUserDefaults standardDefaults]
as an integer (selected index of tab bar controller).
Do this in:
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;
{
[[NSUserDefaults standardDefaults] setInteger:tabBarController.selectedIndex forKey:SelectedTabIndex];
}
On launch, you can load the selected index from defaults using -integerForKey:
and it will default to zero if a value was not found for that key, or if the key was not parsed as an integer.
I wrap the access to the saved index with a method:
- (NSUInteger)tabIndexToSelect;
{
return [[NSUserDefaults standardDefaults] integerForKey:SelectedTabIndex]; // defaults to zero
}
A note about NSUserDefaults
.. until they are syncronized, they are not flushed to disk for persistence. You will notice this if you're debugging and terminate the app, and iOS hasn't automatically synchronized your app's defaults. You can force synchronize, but I prefer to leave it until it's done automatically. To help with cases where the user switches tab, and then quits, add synchronize to - (void)applicationWillResignActive:(UIApplication *)application
and/or - (void)applicationWillTerminate:(UIApplication *)application
.
Referring to the tab order, rather than selected index (my bad!).
You can simply set each of your tab bar items with a unique tag number. (use an enumeration in your app delegate to keep them unique). Then you can do this:
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed;
{
NSArray *tabBarTagOrder = [tabBarController.tabBar.items valueForKey:@"tag"];
[[NSUserDefaults standardDefaults] setObject:tabBarTagOrder forKey:TabTagOrder];
}
To restore the order at launch, you can manually organize the tab bar items in the order restored from defaults, and then set the items
property of the UITabBar
directly.
How to: Save order of tabs when customizing tabs in UITabBarController - i followed this and off we go.
精彩评论