iOS NSAutoLayoutConstraint:未为故事板中的视图设置

iOS NSAutoLayoutConstraint:未为故事板中的视图设置,ios,cocoa-touch,autolayout,Ios,Cocoa Touch,Autolayout,我的ViewController中有来自故事板的视图。我尝试使用以下代码更改其约束: _viewFromStoryboard.translatesAutoresizingMaskIntoConstraints = NO; NSLayoutConstraint *w = [NSLayoutConstraint constraintWithItem:_viewFromStoryboard attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRela

我的ViewController中有来自故事板的视图。我尝试使用以下代码更改其约束:

_viewFromStoryboard.translatesAutoresizingMaskIntoConstraints = NO;

NSLayoutConstraint *w = [NSLayoutConstraint constraintWithItem:_viewFromStoryboard attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f];
NSLayoutConstraint *h = [NSLayoutConstraint constraintWithItem:_viewFromStoryboard attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1.0f constant:0.0f];
NSLayoutConstraint *centerX = [NSLayoutConstraint constraintWithItem:_viewFromStoryboard attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f];
NSLayoutConstraint *centerY = [NSLayoutConstraint constraintWithItem:_viewFromStoryboard attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f];

[self.view addConstraints:@[w, h, centerX, centerY]];

[_viewFromStoryboard setNeedsUpdateConstraints];
在viewDidLayoutSubviews方法中,但约束似乎不会更新


我做错了什么?

视图是否已经在情节提要中设置了约束

要更改已设置的约束,我通常会按CTRL键从故事板中的约束拖动到类标题中,并为我希望能够更改的每个约束添加一个IBOutlet

然后在代码中,只需更改常量值。这样,您就可以更改已在情节提要中设置的约束


我注意到您的代码中也将宽度和高度设置为0,似乎?

您应该调用LayoutIfNeeded方法以满足更新约束…尝试了它,但在更新之前和更新之后调用此[self.view LayoutIfNeeded]都不起作用,因为它不在情节提要中设置。这就是我们设置两个视图的宽度相等的方法,不是吗?这个代码不应该在viewDidLoad中吗?viewDidLayoutSubviews可能会被调用多次,每次您都会添加约束的副本吗?您还记得调用[super viewDidLayoutSubviews]吗?viewDidLoad似乎没有改变,即使在viewDidLoad中设置视图的位置也不起作用。运行它时,您实际看到的是什么?是1您看到的视图与故事板中的视图一样,其布局没有改变,还是2您什么也看不到,还是3其他什么?控制台日志中是否存在任何约束错误或任何其他错误?