我有一个包含两个新约束的数组。
当我设置这些约束时,按钮从superview的中心放置20和90像素。 我想从底部按下20px,从superview右边按90px。 我究竟做错了什么? 我创建了一个包含两个约束的数组:
NSLayoutConstraint *bottomTrailingConstraint = [NSLayoutConstraint constraintWithItem:_gameSettingsButton
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:_gameSettingsButton.superview
attribute:NSLayoutAttributeTrailing
multiplier:1.0f
constant:90.0f];
NSLayoutConstraint *bottomSpaceConstraint = [NSLayoutConstraint constraintWithItem:_gameSettingsButton
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:_gameSettingsButton.superview
attribute:NSLayoutAttributeBottom
multiplier:1.0f
constant:20.0f];
_bottomConstraintsArray = @[bottomTrailingConstraint, bottomSpaceConstraint];
我删除旧约束,然后添加新约束:
NSArray *oldconstraints = _gameSettingsButton.constraints;
[_gameSettingsButton.superview removeConstraints: oldconstraints];
[_gameSettingsButton.superview addConstraints:_bottomConstraintsArray];
我也试过:[_gameSettingsButton.superview updateConstraints]但是没有改变。
非常感谢任何帮助。
答案 0 :(得分:4)
此:
NSLayoutConstraint *bottomTrailingConstraint = [NSLayoutConstraint constraintWithItem:_gameSettingsButton
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:_gameSettingsButton.superview
attribute:NSLayoutAttributeTrailing
multiplier:1.0f
constant:90.0f];
表示:
_gameSettingsButton.trailing == _gameSettingsButton.superview.trailing * 1 + 90
这将使按钮的后缘位于超视图之外。假设从左到右的布局(所以"尾随"表示"右"),按钮的右边缘将是超级视图右侧的90个点。
同样,这:
NSLayoutConstraint *bottomSpaceConstraint = [NSLayoutConstraint constraintWithItem:_gameSettingsButton
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:_gameSettingsButton.superview
attribute:NSLayoutAttributeBottom
multiplier:1.0f
constant:20.0f];
表示:
_gameSettingsButton.bottom == _gameSettingsButton.superview.bottom * 1 + 20
同样,这会将按钮放在superview之外。按钮的下边缘将从超视图的底部向下20点。
您要么交换第一项和第二项,要么取消常数。
此外,您正在从按钮查询约束,然后从超级视图中删除这些约束。好吧,既然你查询的约束不在superview上,那就什么都不做了。 (实际上,你的查询结果可能是一个空数组,因为没有任何东西会给按钮本身添加任何约束。)你可能想要查询superview上的约束但我怀疑会有与你不喜欢的按钮无关的限制#39; t想要删除。因此,您需要记住为按钮设置的约束(可能在实例变量中)并删除它们。如果在IB中设置了初始约束,那么您需要设置一个出口来跟踪它们。