2
cell.bodyText.numberOfLines = 0

cell.bodyText.text = newsBody
cell.bodyText.sizeToFit()

I set the number of lines to 0 because the number of lines can vary (I am retrieving news articles and since every news article is obviously different in length, numberOfLines is 0)

If I do not use sizeToFit() after assinging newsBody to the label, and check the label height (cell.bodyText.frame.size.height), I get really large numbers (when I tested it, an article that had 25 lines of text, the height was apparently 4000). If I use sizeToFitand then check the height, I get 21 no matter how short or long the label is. (21 is the height I set the UILabel in the storyboard).

How can I get an accurate representation of how many lines are in the UILabel or even just the height of the label?

4

1 回答 1

1

我假设你正在做这项工作tableView(_:cellForRowAtIndexPath:)。这对于查询最终布局是不可靠的。尝试使用委托方法tableView(_:willDisplayCell:forRowAtIndexPath:)。这是在显示单元格之前立即调用的,并且是解决任何最终布局问题的合适位置,因为此时所有内容都已应用。

于 2015-11-15T22:39:58.423 回答