Skip to content

Instantly share code, notes, and snippets.

@acalism
Last active July 12, 2018 14:48
Show Gist options
  • Select an option

  • Save acalism/4de41dca23e6625c4bc5f396eb59d587 to your computer and use it in GitHub Desktop.

Select an option

Save acalism/4de41dca23e6625c4bc5f396eb59d587 to your computer and use it in GitHub Desktop.
Pitfalls in calculating label size
// 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:) 来解决问题
@acalism
Copy link
Copy Markdown
Author

acalism commented Jul 12, 2018

-[UILabel sizeThatFits:] ignores numberOfLines property,
so textRect(forBounds: is nearly always preferred.
https://stackoverflow.com/questions/5041874/uilabels-sizetofit-sizethatfits-ignore-the-numberoflines-property

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment