当父级的大小减小时,哪些自动布局约束允许子视图压缩到 0 大小?
Posted
技术标签:
【中文标题】当父级的大小减小时,哪些自动布局约束允许子视图压缩到 0 大小?【英文标题】:What auto layout constraints lets a subview to compress to 0 size when the parent's size decreases? 【发布时间】:2015-02-02 17:37:33 【问题描述】:试图弄清楚我需要向视图-子视图布局层次结构添加哪些约束,以允许子视图在父视图的大小发生变化时自动调整大小。不故意使用界面生成器,translatesAutoresizingMaskIntoConstraints
设置为 NO
用于所有参与视图。
下面是一段代码sn-p,它试图描述这种情况:
UIView *canvas = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
UIView *container = [[UIView alloc] initWithFrame:CGRectZero];
container.translatesAutoresizingMaskIntoConstraints = NO;
[canvas addSubview:container];
NSNumber *height = @(50);
NSNumber *margin = @(10);
NSDictionary *metrics = NSDictionaryOfVariableBindings(height, margin);
NSDictionary *views = NSDictionaryOfVariableBindings(container);
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(margin)-[container(height)]" options:0 metrics:metrics views:views];
[canvas addConstraints:constraints];
NSLayoutConstraint *containerHeightConstraint = [constraints objectAtIndex:1]; // Know this is unsafe and shouldn't use the visual format in this case, but visual format serves SO purposes better
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|-(margin)-[container]-(margin)-|" options:0 metrics:nil views:views];
[canvas addConstraints:constraints];
UIView *subView = [[UIView alloc] initWithFrame:CGRectZero];
subView.translatesAutoresizingMaskIntoConstraints = NO;
[container addSubview:subView];
margin = @(5);
metrics = NSDictionaryOfVariableBindings(margin);
views = NSDictionaryOfVariableBindings(subView);
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(margin)-[subView]-(margin)-|" options:0 metrics:metrics views:views];
[container addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|-(margin)-[subView]-(margin)-|" options:0 metrics:metrics views:views];
[container addConstraints:constraints];
[container layoutIfNeeded]; // Layout before animation
containerHeightConstraint.constant = 0;
[UIView animateWithDuration:animationDuration animations:^
[container layoutIfNeeded]; // Animate container to 0 height
completion:nil];
问题是我需要添加哪些约束来模拟 Interface Builder 创建的自动调整掩码约束,并允许上面示例中的 subView
在 container
缩小时缩小到 0 高度。
如果您还可以解释这些约束的机制,这将有助于我更好地理解自动布局。
【问题讨论】:
【参考方案1】:您只需要在容器调整大小时为您的子视图设置高度和宽度常量约束。
【讨论】:
以上是关于当父级的大小减小时,哪些自动布局约束允许子视图压缩到 0 大小?的主要内容,如果未能解决你的问题,请参考以下文章