【发布时间】:2017-02-20 10:42:43
【问题描述】:
我想创建一个自定义视图,可以根据内容自行调整大小。
例如,我为一个UILabel设置了水平约束,然后它会自动换行。
我想知道系统如何在布局之前知道标签的宽度?
我打印 updateConstraints 、 layoutSubviews 和 intrinsicContentSize 方法来尝试了解一切进展情况。
首先,我设置 numberOfLine = 1,所以日志是这样的:
TagLabel will updateConstraints
TagLabel intrinsicContentSize 447.5 20.5
TagLabel did updateConstraints
TableViewCell will updateConstraints
TableViewCell did updateConstraints
TableViewCell will layoutSubviews
TableViewCell did layoutSubviews
TagLabel will layoutSubviews
TagLabel did layoutSubviews
TagLabel will layoutSubviews
TagLabel did layoutSubviews
然后我设置 numberOfLine = 0,日志变化如下:
TagLabel will updateConstraints
TagLabel intrinsicContentSize 428.0 20.5
TagLabel did updateConstraints
TableViewCell will updateConstraints
TableViewCell did updateConstraints
// extra calls
TagLabel will updateConstraints
TagLabel intrinsicContentSize 428.0 20.5
TagLabel did updateConstraints
TagLabel intrinsicContentSize 428.0 20.5
TagLabel intrinsicContentSize 371.0 41.0
TableViewCell will layoutSubviews
TableViewCell did layoutSubviews
// extra calls
TagLabel will updateConstraints
TagLabel intrinsicContentSize 428.0 20.5
TagLabel did updateConstraints
TagLabel will updateConstraints
TagLabel intrinsicContentSize 428.0 20.5
TagLabel did updateConstraints
TagLabel will updateConstraints
TagLabel intrinsicContentSize 371.0 41.0
TagLabel did updateConstraints
TagLabel will updateConstraints
TagLabel intrinsicContentSize 428.0 20.5
TagLabel did updateConstraints
TagLabel will updateConstraints
TagLabel intrinsicContentSize 371.0 41.0
TagLabel did updateConstraints
TagLabel will layoutSubviews
TagLabel did layoutSubviews
TagLabel will layoutSubviews
TagLabel did layoutSubviews
我发现系统在layoutSubviews之前正确计算了标签的高度。
那么系统是如何知道标签的宽度从而计算出layoutSubviews之前的高度呢?
欣赏。
【问题讨论】:
-
我认为
UILabel.preferredMaxLayoutWidth与这个问题有关。不过,我不知道系统是如何知道layoutSubviews之前的宽度的。
标签: ios autolayout uilabel