关于如何正确定义在删除给定视图时会折叠视图之间的空间的约束,我感到有点难过.我尝试添加大于或等于关系的垂直约束,但是,似乎不满足约束的最小距离.
例如,给定以下具有三个约束V的布局:[A] -5- [B],V:[B] -5- [C],并且V:[A] – (> = 5) – [C ]:
[ View A ] | 5 pt | [ View B ] | 5 pt | [ View C ]
删除视图B后,我希望它看起来像这样:
[ View A ] | 5 pt | [ View C ]
但它看起来像这样:
[ View A ] | 5 pt + 5 pt + height of view B | [ View C ]
解决方法
如果您正在寻找可扩展的,那么您可能不得不在代码中执行此操作.我喜欢用的东西
UIView *superView = /* whatever the superview of your views is,probably self.view in a lot of cases */ NSArray *arrViews = [NSArray arrayWithObjects:/* put only the things you want to show in here,do not put the hidden things,and put them in order from top to bottom */,nil]; CGFloat buffer = 5; [superView addConstraint:[NSLayoutConstraint constraintWithItem:[arrViews objectAtIndex:0] attribute:NSLayoutAttributetop relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributetop multiplier:1 constant:buffer]]; for (int i = 1; i < arrViews.count; i++) { [superView addConstraint:[NSLayoutConstraint constraintWithItem:[arrViews objectAtIndex:i] attribute:NSLayoutAttributetop relatedBy:NSLayoutRelationEqual toItem:[arrViews objectAtIndex:i-1] attribute:NSLayoutAttributeBottom multiplier:1 constant:buffer]]; } [superView addConstraint:[NSLayoutConstraint constraintWithItem:[arrViews lastObject] attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeBottom multiplier:1 constant:-1*(buffer)]];
这将在顶部项目和超级视图之间放置固定的间距(大小=缓冲区),然后在每个子视图和其正上方的子视图之间,然后在底部视图和超级视图之间.每次从arrViews中删除项目时都需要调用它,然后调用[superView needsLayout].您还需要确保以某种方式设置高度约束,否则您将收到错误.如果一切都是相同的高度,你可以在循环中添加另一行来添加高度约束.