没有故事板的Tabbar的保存和恢复

时间:2013-10-21 11:15:51

标签: iphone ios objective-c ios6 uikit-state-preservation

我正在使用iOS 6保存和恢复(没有故事板),它与导航控制器工作正常,但如果我在主窗口上手动添加Tabbar控制器,我没有被选中选项卡。

例如

  ListViewController *list = [[ListViewController alloc] initWithNibName:@"ListViewController" bundle:nil];
 SettingViewController *setting = [[SettingViewController alloc] initWithNibName:@"SettingViewController" bundle:nil];

 UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:list];
 navigation.restorationIdentifier = @"NavigationControllerID";

 self.tabbar = [[UITabBarController alloc] init];
 self.tabbar.restorationIdentifier = @"TabbarControllerID";
    self.tabbar.viewControllers = @[navigation,setting];

 [[_tabbar.tabBar.items objectAtIndex:0] setTitle:NSLocalizedString(@"List", @"comment")];
 [[_tabbar.tabBar.items objectAtIndex:1] setTitle:NSLocalizedString(@"Setting", @"comment")];

 self.window.rootViewController = self.tabbar;
 [self.window makeKeyAndVisible];

在他的情况下,我每次都会选择第一个标签。我有选择

+ (UIViewController *)viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder

用于设置视图控制器。

1 个答案:

答案 0 :(得分:0)

在Appdelegate中添加此方法

NSString * const AppDelegateRootVCKey = @" AppDelegateRootVCKey";

 - (void)application:(UIApplication *)application willEncodeRestorableStateWithCoder:(NSCoder *)coder {
//Adding last tabbar selected index
[coder encodeObject:[NSString stringWithFormat:@"%d",self.tabbar.selectedIndex]forKey:AppDelegateRootVCKey];

}

   - (BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder {


//Setting Last tabbar selected index
NSString *selectedStr = [coder decodeObjectForKey:AppDelegateRootVCKey];
self.tabbar.selectedIndex = [selectedStr intValue];

return YES;

}