【问题标题】:iOS NSAutoLayoutConstraint: Not being set for views from storyboardiOS NSAutoLayoutConstraint:没有为情节提要的视图设置
【发布时间】:2015-02-10 12:21:29
【问题描述】:

我的 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 方法中,但约束似乎没有更新。

我做错了什么?

【问题讨论】:

  • 你应该调用 LayoutIfNeeded 方法来更新约束...
  • 试过了,还是不行
  • 更新前和更新后调用此 [self.view layoutIfNeeded] 对我有用

标签: ios cocoa-touch autolayout


【解决方案1】:

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

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

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

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

【讨论】:

  • 故事板中没有设置。这就是我们将两个视图的宽度设置为相等的方式,不是吗?
  • 这段代码不应该在viewDidLoad中吗? viewDidLayoutSubviews 可能会被多次调用,并且每次您都会添加约束的副本?你还记得调用 [super viewDidLayoutSubviews] 吗?
  • viewDidLoad 似乎没有改变影响事物(即使在 viewDidLoad 中设置视图的位置也不起作用)。
  • 运行时实际看到的是什么?是 1) 你看到的视图和它在故事板中的一样,它的布局没有改变,还是 2) 你什么也没看到,还是 3) 别的什么?控制台日志中是否有任何约束错误或任何其他错误?
猜你喜欢
  • 2014-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
  • 2014-01-01
相关资源
最近更新 更多