UILabel sizeToFit和约束 [英] UILabel sizeToFit and constraints
问题描述
有没有简单的方法,可以帮助我使用他们的内容大小动态改变依赖视图的位置?
Is there any simple way which can help me to change position of dependent views dynamically using their content size?
我想在列中显示几个视图变化的内容。我希望他们一个接一个放置(我使用约束创建布局,看起来像这样)
I want to show several views in column which all have varying content. And I want them to be placed one after another (I've created layout using constraints which looks like this)
但是每当我更改标签的内容并调用 sizeToFit
,系统似乎忽略布局。
But whenever I change content of labels and call sizeToFit
, system seems to ignore layout.
目前我只对height属性感兴趣,我知道约束rect也可以使用,在过去,我在UIView上写了很多类别来动态改变大小(我猜大家)。但是也许有一种我不知道的简单方法。
At the moment I'm interested only in height property, I know that constraining rect can be used too and in the past I wrote many categories on UIView to change sizes dynamically (I guess everyone did). But maybe there is a simple way which I don't know?
推荐答案
-sizeToFit
不应该被调用,如果你使用自动布局。这是旧系统的一部分。
-sizeToFit
should not be called if you are using auto-layout. That's part of the 'old' system.
看起来IB已经在你的约束中插入了显式高度(标签旁边的竖线表示这一点)。尝试选择标签并按Cmd + =清除这些标签。
It looks like IB has inserted explicit heights into your constraints (the vertical bars next to the labels indicate this). Try selecting the labels and hitting Cmd+= to clear these.
对于多行标签,您还需要在视图控制器中执行以下操作,调整视图大小:
For multiline labels you will also need to do the following in your view controller to make everything work correctly when rotating/resizing the view:
- (void)updateLabelPreferredMaxLayoutWidthToCurrentWidth:(UILabel *)label
{
label.preferredMaxLayoutWidth =
[label alignmentRectForFrame:label.frame].size.width;
}
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
[self updateLabelPreferredMaxLayoutWidthToCurrentWidth:self.label1];
[self updateLabelPreferredMaxLayoutWidthToCurrentWidth:self.label2];
[self updateLabelPreferredMaxLayoutWidthToCurrentWidth:self.label3];
[self.view layoutSubviews];
}
多行标签暴露自动布局的弱点之一。我们必须更新 preferredMaxLayoutWidth
来强制标签回流并调整其高度,否则如果视图被调整大小/旋转,自动布局不会意识到标签需要回流并调整大小。
Multiline labels expose one of the weaknesses of auto-layout. We have to update preferredMaxLayoutWidth
to force the label to reflow and adjust its height, otherwise if the view is resized/rotated, auto-layout does not realize the label needs to be reflowed and resized.
这篇关于UILabel sizeToFit和约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!