如何计算UILabel的高度?

时间:2017-08-03 13:32:05

标签: ios swift uitableview uilabel core-text

我正在尝试根据UILabel的高度设置UITableViewCell的高度。
我的问题类似于this one 但是那个答案中的OC代码现在似乎已被弃用(我不确定,但是找不到它) 我正在使用以下代码来计算标签的高度。

extension String {
    // the length of text in one line
    func size(ofFont font: UIFont) {
        return (self as NSString).size(attributes: [NSFontAttributeName: font])
}

cellForRow:方法中:

let size = text.size(ofFont: font)
let height = ceil(size.width/(UIScreen.main.bounds.width))*size.height

但如果最后一个单词太长而无法显示在一行中,那将是额外的断行  所以,这里出现了虫子 谢谢你的任何建议。

2 个答案:

答案 0 :(得分:3)

您应该使用UITableViewAutomaticDimension

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140

您还应该设置numberOfLines

cell.label.numberOfLines = 0

不要忘记在所有方面设置约束

答案 1 :(得分:3)

在Swift 3中

设置 BackgroundView 约束,如前导,尾随,上下,,请显示图片。

enter image description here

设置 UILabel 约束,例如前导,尾随,顶部,底部

并设置它的属性 numberOfLines = 0

enter image description here

然后你的viewController类ViewDidLoad方法编写这段代码。

override func viewDidLoad() {
        super.viewDidLoad()
        //dynamic tablview
        yourTablview.estimatedRowHeight = 83.0
        yourTablview.rowHeight = UITableViewAutomaticDimension
    }

我希望它适合你。