Domanda

My app uses embed segues to show multiple view controllers on screen at once. I'm trying to implement UIKit state restoration, but the framework is not asking my embedded view controllers to encode and decode their states. This happens automatically with all other types of segues.

Is UIKit state restoration possible with embed segues?

Here is an example application which demonstrates this issue: https://github.com/paulhimes/RestoreEmbeddedTest

È stato utile?

Soluzione

Based on the project you linked to, the trick is to encode the embedded VC from the encode implementation of the container VC.

Altri suggerimenti

You can encode the embed-segue controller properties captured from prepareForSegue or just encode the children as follows:

ContainerController.m

- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {
    [super encodeRestorableStateWithCoder:coder];
    for(UIViewController *cvc in self.childViewControllers){
        if(!cvc.restorationIdentifier){
            continue;
        }
        [coder encodeObject:cvc forKey:cvc.restorationIdentifier];
    }
}

And in the child controller you must implement encode and either not call super or clear the storyboard object. The reason is if you decide to implement viewControllerWithRestorationIdentifierPath and return nil when you do not want the controller to appear (e.g. because of stale data), the embedded controllers would then be needlessly instantiated using the storyboard, which to be honest is very odd it even happens given that returning nil is supposed to prevent restoration going down that path.

EmbeddedController.m

- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {
    // super not called to prevent encoding storyboard
    // or call super and then encode nil for UIStateRestorationViewControllerStoryboardKey
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top