自定义容器视图控制器状态保存

时间:2013-06-17 10:44:59

标签: ios objective-c uiviewcontroller uikit-state-preservation

我需要创建带有标签和2个状态A和B的自定义容器viewcontroller(每个状态由子视图控制器呈现并相互交换)。两个子视图控制器在父容器创建时实例化,默认情况下currentViewController是viewControllerA。所以我在容器viewcontroller中有这样的东西:

@property(weak, nonatomic) id currentViewController;
@property(strong, nonatomic) id viewControllerA;
@property(strong, nonatomic) id viewControllerB;
@property(strong, nonatomic) UILabel* label;

...

// Question here
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.viewControllerA = [ViewControllerA new];
    self.viewControllerB = [ViewControllerB new];
    self.currentViewController = self.viewControllerA;
    [self populateCurrentViewController];
}

- (void)populateCurrentViewController
{
    [self addChildViewController:self.currentViewController];
    [self.view addSubview:self.currentViewController.view];
    [self.currentViewController didMoveToParentViewController:self];
}

- (void)goToState: (UIViewController*)stateController
{
    if(self.currentViewController != stateController)
    {
        [self.currentViewController willMoveToParentViewController:nil];
        [self addChildViewController:state];

        [self transitionFromViewController: self.currentViewController toViewController: stateController
            duration: 0.25 options:UIViewAnimationOptionTransitionFlipFromLeft
            animations:nil
            completion:^(BOOL finished) {
                [self.currentViewController removeFromParentViewController];
                [stateController didMoveToParentViewController:self];
            }];
    }
}

- (void)goToStateA
{
    [self goToState: self.viewControllerA];
    self.label.text = @"A";
}

- (void)goToStateB
{
    [self goToState: self.viewControllerB];
    self.label.text = @"B";
}

我需要保留容器viewcontroller的状态。问题是我必须在第一次创建容器视图控制器和恢复过程时实例化并添加子视图控制器?我必须在哪里恢复儿童视力控制器?

我找到了很多候选人:

-(void)initWithCoder
-(void)awakeFromNib
-(void)viewDidLoad
-(void)viewWillAppear

-(void)decodeRestorableStateWithCoder

恢复过程。

关于这个问题的几点想法。如果使用initWithCoderviewDidLoad创建子视图控制器并将当前viewcontroller作为子视图添加到容器视图控制器,那么在恢复过程之后我需要更改当前视图控制器并在必要时交换它,我认为有什么问题。如果使用viewWillAppear添加当前viewcontroller,则恢复过程是正常的,但可以多次调用此方法。

我认为有两种方法可以恢复恢复子视图控制器:

  1. viewDidLoad中实例化并在-(void)decodeRestorableStateWithCoder:(NSCoder *)coder中恢复[self.viewControllerA decodeRestorableStateWithCoder:coder](我在此处看到 - https://stackoverflow.com/a/16647606/2492707

  2. 完全恢复-(void)decodeRestorableStateWithCoder:(NSCoder *)coder,如self.viewControllerA = [coder decodeObjectForKey: @"AKey"];

  3. 哪种方式更好?

    了解UINavigationController的恢复过程(其中填充了visibleViewController)也可以帮助我。

    提前致谢。

0 个答案:

没有答案