使用 AutoLayout 约束隐藏 UIView [英] Hiding a UIView using AutoLayout constraints

查看:19
本文介绍了使用 AutoLayout 约束隐藏 UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我想从布局中删除一个子视图.它不仅应该被隐藏,而且不应该被视为视图流程"的一部分,可以这么说.一个例子:

From time to time I have a subview that I would like to remove from a layout. Not only should it be hidden, but it should not be considered part of the view's 'flow', so to speak. An example:

我正在寻找一种以编程方式隐藏橙色视图的策略.框的布局及其内容是通过自动布局进行的.需要注意的两点:

I am looking for a strategy to hide the orange view programmatically. The layout of the boxes, and their content, is via autolayout. Two things to note:

  • 橙色框根据内容定义其垂直高度,加上一些用于边距的顶部/底部偏移量.因此,将标签的文本设置为 nil 只会将视图缩小"到其内部边距,它的高度不会为 0.
  • 同样,三个框之间的垂直间距意味着,即使橙色框的高度为 0,红色和黄色之间的间隙也会达到要求的两倍.

我最好的建议是向橙色框添加约束,将其高度设置为 0.为此,我需要对橙色框内的所有垂直约束使用非必需的优先级.同时,容器应更新分隔框的约束的常量.我不太喜欢这种方法,因为橙色框类正在定义它的内部约束,并考虑到它的超级视图的行为.如果橙色框视图公开了一个添加 0 高度约束本身的折叠"方法,也许我可以接受它.

My best suggestion is to add a constraint to the orange box, setting it's height to 0. For this to work, I need to use non-required priorities for all of the vertical constraints inside the orange box. At the same time, the container should update the constant for the constraint that separates the boxes. I don't like this approach so much since the orange box class is defining it's internal constraints with it's superview's behavior in mind. Perhaps I could live with it if the orange box view instead exposes a 'collapse' method that adds the 0 height constraint itself.

有更好的方法吗?

推荐答案

您可以通过在较低优先级的黄色和红色视图之间添加额外约束并在代码中调整优先级来实现此目的.

You can do this by adding an extra constraint between the yellow and red views of a lower priority, and adjusting the priorities in code.

短虚线约束(orangeToRedCon 是出口)的优先级为 999(您不能将必需的优先级更改为非必需的,因此它不是 1000).长虚线约束 (yellowToRedCon) 的优先级为 500,常量为 20.在代码中,您可以隐藏橙色视图,并交换这些优先级,这将导致黄色视图向上移动到您设置的任何值设置为yellowToRedCon 的常数值.

The short dashed constraint (orangeToRedCon is the outlet) has a priority of 999 (you can't change a required priority to a non-required, so that's why it's not 1000). The long dashed constraint (yellowToRedCon) has a priority of 500 and a constant of 20. In code, you can hide the orange view, and swap those priority levels, and that will cause the yellow view to move up to whatever value you've set for the constant value of yellowToRedCon.

-(void)changePriorities {
    self.yellowToRedCon.priority = 999;
    self.orangeToRedCon.priority = 500;
    [UIView animateWithDuration:.5 animations:^{
        self.orangeView.alpha = 0;
        [self.view layoutIfNeeded];
    }];
}

此方法不需要更改橙色视图的高度.

This method doesn't require any changes in the orange view's height.

这篇关于使用 AutoLayout 约束隐藏 UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆