Last active
July 12, 2018 14:48
-
-
Save acalism/4de41dca23e6625c4bc5f396eb59d587 to your computer and use it in GitHub Desktop.
Pitfalls in calculating label size
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 1. 多行文本 | |
| let label = UILabel() | |
| label.font = Font.f14 | |
| label.numberOfLines = 2 // 若此处的行数限定为0(即可无数行),则以下面的 limitedToNumberOfLines 为准;否则两个行数中较小的那个会生效 | |
| label.text = model.svideoInfo.svideoTitle // 多行文本 | |
| let titleRect = label.textRect(forBounds: CGRect(origin: .zero, size: CGSize(width: cellWidth - margins.xInset, height: CGFloat.greatestFiniteMagnitude)), limitedToNumberOfLines: 0) | |
| // 事实上,用sizeThatFits(_:)就好了。 | |
| // 2. 单行文本 | |
| // 如果 label.numberOfLines 为默认值1,那么 label.siztThatFits(maxSize) 不受 maxSize.width 的限制。 | |
| // 这点委实蛋疼。 | |
| // 这意味着,你还得回归 textRect(forBounds:limitedToNumberOfLines:) 来解决问题 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-[UILabel sizeThatFits:]ignoresnumberOfLinesproperty,so
textRect(forBounds:is nearly always preferred.https://stackoverflow.com/questions/5041874/uilabels-sizetofit-sizethatfits-ignore-the-numberoflines-property