将UIView从另一个控制器添加到具有autolayout的UIView

时间:2014-03-13 10:11:43

标签: ios uiview containers autolayout

我尝试将UIViews从不同的UIViewControllers切换到UIViewController内的主容器视图控制器。问题是新的UIView没有调整容器视图大小。我尝试使用此功能,但仍然无法正常工作。在其中一个UIViews里面我有一个UIWebView。

-(void) showViewWithIndex: (NSInteger) index{

    //remove old stuff
    [_containerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

    UIViewController *controllerToShow = _settingsController[index];

    if (controllerToShow) {

        NSLog(@"main height: %f width: %f", _containerView.frame.size.height, _containerView.frame.size.width);

        UIView *controllerViewToShow = controllerToShow.view;

        //clear constaints
        [controllerViewToShow removeConstraints:controllerViewToShow.constraints];
        [_containerView removeConstraints: _containerView.constraints];

        controllerViewToShow.translatesAutoresizingMaskIntoConstraints = NO;

        [_containerView addSubview: controllerToShow.view];

        [_containerView addConstraints:[NSLayoutConstraint
                                   constraintsWithVisualFormat:@"V:|-[controllerViewToShow]-|"
                                   options:NSLayoutFormatDirectionLeadingToTrailing
                                   metrics:nil
                                   views:NSDictionaryOfVariableBindings(controllerViewToShow)]];

        [_containerView addConstraints:[NSLayoutConstraint
                                   constraintsWithVisualFormat:@"H:|-[controllerViewToShow]-|"
                                   options:NSLayoutFormatDirectionLeadingToTrailing
                                   metrics:nil
                                   views:NSDictionaryOfVariableBindings(controllerViewToShow)]];


        //update all views:
        [_containerView layoutIfNeeded];
        [_containerView needsUpdateConstraints];

        [controllerViewToShow layoutIfNeeded];
        [controllerViewToShow needsUpdateConstraints];


        NSLog(@"controllerViewToShow width: %f height: %f", controllerViewToShow.frame.size.height, controllerViewToShow.frame.size.width);

    }

}

0 个答案:

没有答案