问题描述
有什么简单的方法可以帮助我使用它们的内容大小动态改变依赖视图的位置?
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 和约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!