如何使用状态恢复恢复视图控制器的子视图

时间:2014-05-26 13:28:20

标签: ios state-restoration

我正在使用状态恢复来恢复我的应用程序的先前视图和数据。当在第一个视图控制器中单击按钮时,我将推送第二个视图控件。在这种情况下,我能够恢复第二个视图控制器数据。但是如果在第一个视图中单击按钮时,我将第二个View Controller视图作为子视图添加到第一个视图控制器Controller,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 个答案:

答案 0 :(得分:0)

似乎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];
}