gpt4 book ai didi

ios - 自动布局, View 高度取决于 subview 高度

转载 作者:可可西里 更新时间:2023-11-01 06:09:42 24 4
gpt4 key购买 nike

我正在使用自动布局开发一个包含 UILabel 的容器 UIView。我想根据 UILabel 的高度动态地设置容器 View 的高度。

我在容器 View 中添加了这些约束,但我不知道如何判断 UILabel 的高度,因为它是多行 UILabel。

- (void) updateConstraints{

[self removeConstraints:self.constraints];

NSDictionary *views = NSDictionaryOfVariableBindings(_informationLabel);

// -- Constraints

[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[_informationLabel]-5-|"
options:0
metrics:@{}
views:views]];

[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[_informationLabel]-5-|"
options:0
metrics:@{}
views:views]];
[super updateConstraints];}

我已经尝试使用 boundingRectWithSize 计算高度并将高度发送到 metrics 字典中。

在 ViewController 中,我没有指定容器 View 的高度以让它根据 subview 的高度调整大小:

[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-100-[_informationView]"
options:0
metrics:@{}
views:views]];

[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_informationView]-|"
options:0
metrics:@{}
views:views]];

如何使容器 View 高度随着 uilabel 高度的增长而增长?

最佳答案

多行文本(UILabel & NSTextView)的intrinsicContentSize不明确。这是因为高度取决于尚未计算的宽度。为了解决这个问题,你必须允许布局的第一遍,然后设置新添加的属性 preferredMaxLayoutWidth 专门解决这个问题。

// Inside superview
- (void)layoutSubviews
{
[super layoutSubviews];
self.informationLabel.preferredMaxLayoutWidth = self.informationLabel.frame.size.width;
[super layoutSubviews];
}

来源: http://www.objc.io/issue-3/advanced-auto-layout-toolbox.html

关于ios - 自动布局, View 高度取决于 subview 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19875777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com