如何使我的superview调整大小以使其子视图的大小与Autolayout相匹配?

时间:2013-08-05 15:04:19

标签: ios interface-builder autolayout

我有一个UIView(“superview”),它有几个UILabels作为子视图,在Interface Builder中设置。我已启用自动布局,以便一个接一个地正确地隔开列表中的所有标签。这很有效。

我现在要做的是让我的Superview垂直调整大小以匹配我所有标签的高度,我无法弄清楚如何做到这一点。

这是如何运作的?

3 个答案:

答案 0 :(得分:1)

以下是使用可视布局的示例...因此请忽略translatesAutoresizingMaskIntoConstraints业务。

这依赖于容器视图没有任何高度约束这一事实,它似乎依赖于视图之间的间距。系统将调整视图大小以匹配子视图的要求。

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor redColor];

        [self setTranslatesAutoresizingMaskIntoConstraints:NO];

        _labelOne = [[UILabel alloc] init];
        _labelOne.text = @"Banana";
        _labelOne.backgroundColor = [UIColor blueColor];
        [_labelOne setTranslatesAutoresizingMaskIntoConstraints:NO];

        _labelTwo = [[UILabel alloc] init];
        _labelTwo.text = @"Dinosaur";
        _labelTwo.backgroundColor = [UIColor yellowColor];
        [_labelTwo setTranslatesAutoresizingMaskIntoConstraints:NO];

        [self addSubview:_labelOne];
        [self addSubview:_labelTwo];

        NSDictionary *views = NSDictionaryOfVariableBindings(_labelOne, _labelTwo);
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_labelOne]|" options:0 metrics:nil views:views]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_labelTwo]|" options:0 metrics:nil views:views]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[_labelOne(30)]-15-[_labelTwo(30)]-10-|" options:0 metrics:nil views:views]];
    }
    return self;
}

答案 1 :(得分:0)

我知道基本的想法是通过确保每个子视图的垂直维度中的内容压缩阻力和内容拥抱约束不被更高优先级的约束覆盖,使子视图的内在内容大小驱动超视图的高度你添加了。

答案 2 :(得分:-2)

尝试使用UIView方法sizeToFit