删除中间视图时,Autolayout会折叠空间

时间:2014-03-13 16:21:55

标签: ios iphone objective-c autolayout

关于如何正确定义在删除给定视图时会折叠视图之间的空间的约束,我感到有点难过。我尝试添加大于或等于关系的垂直约束,但是,似乎不满足约束的最小距离。

例如,给定以下具有三个约束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 ]

3 个答案:

答案 0 :(得分:8)

您可以添加V:[A] -5- [C],优先级低于1000。

[superview]
    |
[ View A ]
    |             |
   5 pt (1000)    | 
    |             |
[ View B ]       5 pt (999)
    |             |
   5 pt (1000)    |
    |             |
[ View C ]        

答案 1 :(得分:3)

如果您正在寻找可扩展的内容,那么您可能需要在代码中执行此操作。我使用像

这样的东西
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)]]; 

这将在顶部项目及其超级视图之间设置固定间距(大小= buffer),然后在每个子视图与其正上方的子视图之间,然后在底部视图和超级视图之间。每次从arrViews移除项目时,您都必须拨打此电话,然后拨打[superView needsLayout]。您还需要确保以某种方式设置高度约束,否则您将收到错误。如果一切都是相同的高度,你可以在循环中添加另一行来添加高度约束。

答案 2 :(得分:1)

您需要以编程方式重新连接约束,以便View CView B的约束指向View A,并确保从View A到{{1}的约束}} 已移除。 执行此操作后,在包含这些视图的超级视图上调用View B