的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属性,我知道矩形约束还可以用在过去,我写了很多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屋!