我在故事板中设置了一个视图控制器,启用了autolayout,我正在寻找一种方法来更改约束,以允许我的视图旋转到横向和重新排列屏幕上的按钮。当我尝试下面的代码时,我得到了大约二十几个"无法满足约束,打破约束......"我无法真正解码的消息。
有没有办法用编程方式指定的约束动态替换故事板中的约束?我想完全覆盖我在故事板中定义的按钮的布局。
-(void)updateViewConstraints
{
[super updateViewConstraints];
self.loginButton.translatesAutoresizingMaskIntoConstraints = NO;
self.getStartedButton.translatesAutoresizingMaskIntoConstraints = NO;
self.takeTourButton.translatesAutoresizingMaskIntoConstraints = NO;
[self.loginButton removeConstraints:self.loginButton.constraints];
[self.getStartedButton removeConstraints:self.getStartedButton.constraints];
[self.takeTourButton removeConstraints:self.takeTourButton.constraints];
one = self.loginButton;
two = self.getStartedButton;
three = self.takeTourButton;
NSDictionary *metrics = @{@"height":@50.0,@"width":@100.0,@"leftSpacing":@110.0};
NSDictionary *views = NSDictionaryOfVariableBindings(one,two,three);
[self.view removeConstraints:activeTestLabelConstraints];
[activeTestLabelConstraints removeAllObjects];
if(isRotatingToLandscape)
{
[self registerConstraintsWithVisualFormat:@"|-[one(two)]-[two(three)]-[three]-|" options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:metrics views:views];
[self registerConstraintsWithVisualFormat:@"V:[one(height)]-|" options:0 metrics:metrics views:views];
}else
{
[self registerConstraintsWithVisualFormat:@"|-leftSpacing-[one(width)]" options:0 metrics:metrics views:views];
[self registerConstraintsWithVisualFormat:@"[two(width)]" options:0 metrics:metrics views:views];
[self registerConstraintsWithVisualFormat:@"[three(width)]" options:0 metrics:metrics views:views];
[self registerConstraintsWithVisualFormat:@"V:[one(height)]-[two(75)]-[three(100)]-|" options:NSLayoutFormatAlignAllCenterX metrics:metrics views:views];
}
}
更新了Rob的回答,这里是删除我使用的约束的方法
-(void)removeConstraintForView:(UIView*)viewToModify
{
UIView* temp = viewToModify;
[temp removeFromSuperview];
[self.view addSubview:temp];
}
答案 0 :(得分:10)
听起来您只想删除视图上的所有约束。由于对视图的约束通常由视图的祖先保持,因此如何轻松地删除所有约束并不明显。但实际上很容易。
从视图层次结构中删除视图会删除视图与其外部视图之间的任何约束。因此,只需从超级视图中删除您的视图,然后将其添加回来:
// Remove constraints betwixt someView and non-descendants of someView.
UIView *superview = someView.superview;
[someView removeFromSuperview];
[superview addSubview:someView];
如果someView
及其后代之间存在任何约束,那么这些约束可能由someView
本身保留(但不能由someView
的任何后代持有)。如果您还想删除这些约束,可以直接删除:
// Remove any remaining constraints betwixt someView and its descendants.
[someView removeConstraints:[someView constraints]];