我有一个表格视图和一个单元格。该单元格包含三个标签:标头标签和两个标签,每个标签彼此下面。有时,如果它们不包含数据,则需要在下面隐藏这两个标签,然后将“标题标签”的“顶部空间到容器”更改为“ Y中心到容器”。当然,当两个标签包含数据时,将约束恢复原状。这是一个简单的演示项目的屏幕截图,仅用于展示这个想法:
UPDATE Max MacLeod answer pointed to right direction. The trick is to push header label down when first and second labels are hidden. So we need to set bottom space to container view for first and second labels instead of creating top space to container view for header label. And hiding/unhiding should be done by having height outlets (height constraints for first and second label) and setting their constant values to zero (and setting back value when unhiding). I also uploaded the source code example to Github.
Select the header label, and one of the lower labels, and add a new vertical space constraint reflecting the gap between them. Next, remove the header label Top space to container constraint. Maybe you already have this (can't quite see from the screen grab). If you do, that's good.
Now, create two height constraints for each lower label. IBOutlet
those to your class.
Then, hide those two lower labels whenever you need to by setting each height constraint's constant
to 0.f
.
That will render them invisible and lower the header label above so that it is now vertically centered Y in the container.
Will go through the steps once more (was too long for a comment!). Sequence matters with IB as first you must add a new constraint before you can delete the old one. Temporarily you will have one superfluous constraint. It's because IB won't allow ambiguity. So, first add the new vertical space constraint. That will define the Y position of the upper label. Then, remove the superfluous vertical space to container constraint from the upper label. Now that label will be Y positioned using the vertical space relative to the lower labels. Next, add the height constraints for each lower label and link to the class with an IBOutlet. One other thing, actually you will need the lower labels to be constrained to the container with a bottom space constraint. When their height is reduced to zero, they will disappear, and the upper label will move lower to assume the Y center position.
要还原,只需将constant
back设置为原始值。
这比添加/删除约束(一种繁重的操作)要好得多。请注意,您可能希望将两个下部标签添加到“容器”视图中,以便可以将它们显示/隐藏为一个。另外,由于您确实希望垂直空间位于上部标签和两个下部标签之间,而不仅仅是一个之间,所以它会整理代码。
另请参阅我的答案AutoLayout具有隐藏的UIViews?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句