强制倍增器在Interface Builder约束上更新

时间:2014-09-21 00:13:58

标签: objective-c interface-builder nslayoutconstraint

我在Interface Builder中为UIView创建了一个高度约束,将高度设置为= superview。我将乘数设置为superview宽度的1/3。这很好用,它将iPhone 5 / 5S的高度设置为~107pts。

对于更宽的屏幕,我想将乘数设置为1/4;我想我可以使用Size Classes来做到这一点,但我不确定这是最好的方法吗?

在我的viewWillAppear视图控制器方法中,我尝试过以下操作;不管我做了什么,它的高度仍然只有~107pts。请注意,_controlsAspectRatio是IB约束的IBOutlet

_controlsAspectRatio = [NSLayoutConstraint constraintWithItem:_controlsAspectRatio.firstItem attribute:_controlsAspectRatio.firstAttribute relatedBy:_controlsAspectRatio.relation toItem:_controlsAspectRatio.secondItem attribute:_controlsAspectRatio.secondAttribute multiplier:1.0f/4.0f constant:0];

// I've tried several combinations of several layout refresh options, to no avail
[_controlsContainer setNeedsUpdateConstraints];
[_controlsContainer setNeedsLayout];
[_controlsContainer layoutIfNeeded];
NSLog(@"%0.4f - %0.4f", _controlsContainer.frame.size.height, _controlsAspectRatio.multiplier);

// Output: 106.6667 - 0

1 个答案:

答案 0 :(得分:0)

必须删除原始内容并添加一个全新的约束:

NSLayoutConstraint* newControlsAspectRatio = [NSLayoutConstraint constraintWithItem:_controlsAspectRatio.firstItem attribute:_controlsAspectRatio.firstAttribute relatedBy:_controlsAspectRatio.relation toItem:_controlsAspectRatio.secondItem attribute:_controlsAspectRatio.secondAttribute multiplier:1.0f/4.0f constant:0];
[self.view removeConstraint:_controlsAspectRatio];
[self.view addConstraint:newControlsAspectRatio];
[_controlsContainer layoutIfNeeded];
NSLog(@"%0.4f - %0.4f", _controlsContainer.frame.size.height, newControlsAspectRatio.multiplier);