如何使用状态恢复来恢复视图控制器的子视图
Posted
技术标签:
【中文标题】如何使用状态恢复来恢复视图控制器的子视图【英文标题】:How to restore subview of view controller using state restoration 【发布时间】:2014-05-26 13:28:20 【问题描述】:我正在使用状态恢复来恢复我的应用程序以前的视图和数据。当在第一个视图控制器中单击一个按钮时,我将推动第二个视图控件。在这种情况下,我能够恢复第二个视图控制器数据。但是如果当在第一个视图控制器中单击按钮时,我将第二个视图控制器视图作为子视图添加到第一个视图控制器,在第二个视图控制器中未调用 encodeRestorableStateWithCoder:和 decodeRestorableStateWithCoder:。无法恢复第二个视图控制器数据。我需要做任何其他配置吗恢复子视图数据?
//Firstviewcontroller
-(IBAction)moveToNextViewController:(id)sender
SecondVeiwController *sec_VC=[[SecondVeiwController alloc]initWithNibName:@"SecondVeiwController" bundle:[NSBundle mainBundle ]];
sec_VC.restorationIdentifier=@"SecondVeiwController";
[self.view addSubview:tab_cnt_1.view];
//Secondviewcontroller
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
// Custom initialization
self.restorationIdentifier=@"Secondviewcontroller";
self.restorationClass=[self class];
return self;
+(UIViewController *)viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder
UIViewController * myViewController =
[[Secondviewcontroller alloc]
initWithNibName:@"Secondviewcontroller"
bundle:[NSBundle mainBundle]];
return myViewController;
【问题讨论】:
【参考方案1】:ios 似乎没有跟踪子视图,您必须对 SecondViewController 进行编码,然后将其解码并添加为子视图控制器,并将其视图作为子视图。
//FirstViewController
-(void)encodeRestorableStateWithCoder:(NSCoder *)coder
[super encodeRestorableStateWithCoder:coder];
[coder encodeObject:self.childViewControllers[0] forKey:@"childVC"];
-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
[super decodeRestorableStateWithCoder:coder];
UIViewController *v = [coder decodeObjectForKey:@"childVC"];
[self addChildViewController:v];
[self.view addSubview:v.view];
//SecondViewController
-(void)encodeRestorableStateWithCoder:(NSCoder *)coder
[super encodeRestorableStateWithCoder:coder];
[coder encodeObject:self.view.backgroundColor forKey:@"bgColor"];
-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
[super decodeRestorableStateWithCoder:coder];
UIColor *bgColor = [coder decodeObjectForKey:@"bgColor"];
[self.view setBackgroundColor:bgColor];
【讨论】:
以上是关于如何使用状态恢复来恢复视图控制器的子视图的主要内容,如果未能解决你的问题,请参考以下文章