将子控制器添加到 table 视图单元格时不会调用 viewWillAppear

viewWillAppear is not called when add child controller to table view cell

当我将子视图控制器添加到 table 视图单元格时,看起来 viewWillAppear 没有调用子视图控制器,只有 viewDidAppear.

Table 视图控制器方法:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCellWithIdentifier("ShopInfoTableViewCell", forIndexPath: indexPath) as! ShopInfoTableViewCell
    self.addChildViewController(self.shopInfoViewController, toView: cell.containerView)
    return cell
}

View Controller类方法:

- (void)addChildViewController:(UIViewController *)childController toView:(UIView *)view
{
    [self addChildViewController:childController];
    [view addSubview:childController.view];
    [childController didMoveToParentViewController:self];

    [childController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_top);
        make.bottom.equalTo(view.mas_bottom);
        make.left.equalTo(view.mas_left);
        make.right.equalTo(view.mas_right);
    }];
}

知道为什么会这样吗?

- (void)addChildViewController:(UIViewController *)childController toView:(UIView *)view
{
    [self addChildViewController:childController];

    //add this
    [childController beginAppearanceTransition:YES animated:YES];
    [view addSubview:childController.view];
    [childController endAppearanceTransition];

    [childController didMoveToParentViewController:self];

    [childController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_top);
        make.bottom.equalTo(view.mas_bottom);
        make.left.equalTo(view.mas_left);
        make.right.equalTo(view.mas_right);
    }];
}

同样,当你想消失时,你应该调用这个

    [childController beginAppearanceTransition:NO animated:YES];
    [childController.view removeFromSuperview];
    [childController endAppearanceTransition];

对于@adali 的回答,我会更改:

[childController beginAppearanceTransition:YES animated:YES];

作者:

[childController willMoveToParentViewController:self];

所以最后会是:

[self addChildViewController:childController]; //add the child on childViewControllers array
[childController willMoveToParentViewController:self]; //viewWillAppear on childViewController
[self.containerView addSubview:childController.view]; //add childView whenever you want
[childController didMoveToParentViewController:self]; //viewDidAppear on childViewController

而且非常重要,所有这些都必须在包含children的viewController已经执行了它的viewWillAppear生命周期函数后调用