How to restore subview of view controller using state restoration

424 Views Asked by At

I am using state restoration to restore previous views and data for my app.When a button is clicked in first view controller I am to pushing second view control.In this case I am able to restore second view controller data.But if I add second View Controller view as subview to first view controller when button is clicked in first view Controller, encodeRestorableStateWithCoder: and decodeRestorableStateWithCoder: were not called in second view controller.Unable to restore second view controller data.Do I need to do any other configurations to restore subview data ?

//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

There are 1 best solutions below

0
On

It seems that iOS does not keep track of subviews, you have to encode the SecondViewController and then decode and add it as a child view controller with its view as a subview.

//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];
}