如何计算 UILabel 的高度?
How to calculate the height of a UILabel?
我正在尝试根据 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
但如果最后一个字太长无法在一行中显示,则需要额外换行。
所以,bug来了。
感谢您的任何建议。
你应该使用UITableViewAutomaticDimension
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140
你还应该设置numberOfLines
cell.label.numberOfLines = 0
不要忘记在所有方面设置约束
在Swift3
设置BackgroundView约束,如前导、尾随、顶部、底部,请显示图像。
设置UILabel约束,如leading, trailing, top, bottom
并设置为 属性 numberOfLines = 0
然后在您的 viewController class ViewDidLoad 方法中编写此代码。
override func viewDidLoad() {
super.viewDidLoad()
//dynamic tablview
yourTablview.estimatedRowHeight = 83.0
yourTablview.rowHeight = UITableViewAutomaticDimension
}
希望对你有用。
我正在尝试根据 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
但如果最后一个字太长无法在一行中显示,则需要额外换行。
所以,bug来了。
感谢您的任何建议。
你应该使用UITableViewAutomaticDimension
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140
你还应该设置numberOfLines
cell.label.numberOfLines = 0
不要忘记在所有方面设置约束
在Swift3
设置BackgroundView约束,如前导、尾随、顶部、底部,请显示图像。
设置UILabel约束,如leading, trailing, top, bottom
并设置为 属性 numberOfLines = 0
然后在您的 viewController class ViewDidLoad 方法中编写此代码。
override func viewDidLoad() {
super.viewDidLoad()
//dynamic tablview
yourTablview.estimatedRowHeight = 83.0
yourTablview.rowHeight = UITableViewAutomaticDimension
}
希望对你有用。