所以我有一个名为 self.content
的 super View ,我向它添加了 2 个 subview ,即 self.bg1
和 self.bg2
分别。最初我希望 self.bg2
位于 self.content
的右边界之外。用户应该能够使用按钮调用 self.bg2
。点击按钮时,self.bg1
移动到一个位置,使其右边缘接触 self.content
的左边缘。这是我编写的代码,但它似乎仅在用户从 self.bg1
切换到 self.bg2
时才起作用(不能向后工作)
//BG1
self.bg1 = [[UIView alloc]init];
[self.bg1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.content addSubview:self.bg1];
//BG2
self.bg2 = [[UIView alloc]init];
[self.bg2 setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.content addSubview:self.bg2];
self.viewsDictionary = @{@"bg1":self.bg1,
@"bg2":self.bg2};
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:[bg1(%f)]",self.view.frame.size.width] options:0 metrics:nil views:self.viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[bg1]|" options:0 metrics:nil views:self.viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:[bg2(%f)]",self.view.frame.size.width] options:0 metrics:nil views:self.viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[bg2]|" options:0 metrics:nil views:self.viewsDictionary]];
//self.bGConstraint is an NSArray
self.bGConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[bg1]-[bg2]" options:0 metrics:nil views:self.viewsDictionary];
[self.view addConstraints: self.bGConstraint];
在 switchToBG1
方法中我有:
[self.view removeConstraint:[self.bGConstraint objectAtIndex:0]];
self.bGConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[bg1]-[bg2]" options:0 metrics:nil views:self.viewsDictionary];
[self.view addConstraints: self.bGConstraint];
与 switchToBG2
类似:
[self.view removeConstraint:[self.bGConstraint objectAtIndex:0]];
self.bGConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[bg1]-[bg2]|" options:0 metrics:nil views:self.viewsDictionary];
[self.view addConstraints: self.bGConstraint];
最后 layoutIfNeeded
在 UIView AnimationWithDuration...
*编辑:
从 BG1 切换到 BG2(即从左到右)时的动画成功执行,没有任何错误,但是当我尝试从右到左(BG2 回到 BG1)时,系统向我抛出一个 Unable to同时满足约束。
错误消息。
我在这里做错了什么?提前致谢!
最佳答案
您所做的看起来是正确的想法,因此您的约束交换逻辑可能有问题,这会导致您的第二个约束中的某些内容与您的第一组约束中已经存在的某些内容发生冲突。为了轻松防止这种情况,请以这种方式构建它:
在前面,存储所有 bg1
和bg2
的约束,一个 在 中一个 属性,以及所有 将它们定位到另一个 属性中的other 位置的约束。现在到了交换的时候,换掉所有旧的并换入所有新的。这样你就不会把自己弄糊涂了,而且可以保证一致性。
换句话说,您的代码(仅切换一个约束)试图变得太聪明。最好保持简单和愚蠢(并使其正常工作)!
关于ios - 使用 NSLayoutConstraints 将 View 放置在其 super View 的边界之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25185837/