计算 UILabel 上的行数
我已将 UILabel 上的行数设置为 2,因为这是我想要在 UILabel 上显示的最大行数,然后任何文本都会被截断,而不是将其换行到第三行。
这个 UILabel 是 UITableViewCell 的一部分,我想根据标签的高度或标签上的文本行数更改单元格的高度。如果文本为一行,则表视图的高度将比文本为 2 行时小一些。
我的返回 UILabel 行数的函数有时会返回正确的行数,有时即使文本换行为 2 行,它也会返回计数为 1。
func isTextWrapped() -> Bool {
return countOfLabelLines() >= 2
}
func countOfLabelLines(honorConstraints: Bool = false) -> Int {
if let labelText = self.text as NSString? {
let attributes = [NSAttributedString.Key.font : self.font]
// Needed to consider the constraints on the label.
if honorConstraints {
self.layoutIfNeeded()
}
let labelSize = labelText.boundingRect(with: CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes as [NSAttributedString.Key : Any], context: nil)
return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
}
return 0
?
如何返回 UILabel 上显示的正确行数,即,如果文本未换行,则返回 1 行;如果文本换行,则返回 2 行
我正在使用自定义表视图单元格,它使用可重用的 id 出列。
I have set number of lines on UILabel as 2, since that's the max number of lines I want to show on UILabel and then any text will get truncated instead of wrapping it on 3rd line.
This UILabel is part of UITableViewCell and I want to change the height of the cell, based on the height of the label or based on the number of lines of text on the label. If the text is one line, then the table view's height will be little smaller than if the text is of 2 lines.
My function to returning the number of lines on a UILabel sometimes returns correct number of lines and sometimes it returns count as 1 even if the text is wrapped to 2 lines.
func isTextWrapped() -> Bool {
return countOfLabelLines() >= 2
}
func countOfLabelLines(honorConstraints: Bool = false) -> Int {
if let labelText = self.text as NSString? {
let attributes = [NSAttributedString.Key.font : self.font]
// Needed to consider the constraints on the label.
if honorConstraints {
self.layoutIfNeeded()
}
let labelSize = labelText.boundingRect(with: CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes as [NSAttributedString.Key : Any], context: nil)
return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
}
return 0
}
How can I return the correct number of lines displayed on UILabel i.e. 1 if text is not wrapped or 2 if text is wrapped?
I am using a custom table view cell which dequeues using reusable id.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的表视图仅显示文本,还有另一种方法可以做到这一点。您可以将表格单元格高度设置为动态,而不是使用传入的高度。
更多详细信息,您可以检查以下链接: 自动调整大小(动态高度)表格视图的问题细胞
There is another way to do this if your table view only to display text. Instead of using the height you pass in you can set the table cell height to be dynamic.
More further information you can check the following link: Problems with autoresizing (dynamic height) tableview cells