updateViewConstraints给出了"不可能设置具有视图层次结构的布局,无法用于约束"

时间:2017-09-09 00:57:08

标签: ios objective-c nslayoutconstraint

我有一个View Controller,可以在ViewDidLoad中查看子视图控制器。

- (IBAction)left_seg1:(id)sender {                
            [mapVC layoutMapView];
            [self.view addSubview:mapVC.view];
            NSLog(@"num 1");
            _tagTwo = 3;
            return;
}

然后将此VC添加为IBAction方法中的子视图:

- (void)updateViewConstraints{
    self.view.translatesAutoresizingMaskIntoConstraints = NO;
    mapVC.view.translatesAutoresizingMaskIntoConstraints = NO;

    NSLayoutConstraint* trailConstrain=[NSLayoutConstraint constraintWithItem:mapVC.view attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:10];
    NSLayoutConstraint* leadingConstrain=[NSLayoutConstraint constraintWithItem:mapVC.view attribute:NSLayoutAttributeLeading   relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0 constant:10];
    [self.view addConstraints:@[trailConstrain, leadingConstrain]];

}

我正在尝试为子视图创建关于其父视图的约束。在我尝试这样做时,我已将updateViewConstraints添加到父类。

Assertion failure in -[UIView _layoutEngine_didAddLayoutConstraint:
roundingAdjustment:mutuallyExclusiveConstraints:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.7.47/NSLayoutConstraint_UIKitAdditions.m:649
    **Impossible to set up layout with view hierarchy unprepared for constraint**

但是,这会生成以下运行时异常:

viewDidLoad

我查看了其他主题,问题是他们在public class MyThing<T> { private static int NumberOfCallsToFoo; public void Foo(T item) { NumberOfCallsToFoo++; ... } } 中设置了约束,但我还没有这样做。

1 个答案:

答案 0 :(得分:0)

(1)永远不要永远不要打电话给viewDidLoad。这不是你打电话的方法。立即删除该行。

(2)您的代码存在的问题是您不知道何时会调用它。添加一项检查以确保您的界面中有mapVC.view;如果没有,请不要运行该代码。

(3)。您不仅可以获取视图控制器的视图并将其插入您的界面。您必须充当父视图控制器。你不是那样做的。这是非法的。