【发布时间】:2021-07-15 14:49:05
【问题描述】:
我在单元格上有 2 个标签。如果标签只显示一行文本,则单元格看起来不错。但是,如果有更多文本并且标签上的行被包裹起来,那么它上面的标签/文本就会超出单元格。附上图片。
我当前的代码:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 68.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Code to dequeue reusable cell.
self.titleLabel.text = "This is a very very long text for the title label. Testing testing"
self.subTitleLabel.text = "This is a very very long text for the sub title label. Testing testing the wrapping"
self.titleLabel.sizeToFit()
self.titleLabel.layoutIfNeeded()
self.subTitleLabel.sizeToFit()
self.subTitleLabel.layoutIfNeeded()
}
解决方案我尝试修复它:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Code to dequeue reusable cell.
self.titleLabel.text = "This is a very very long text for the title label. Testing testing"
self.subTitleLabel.text = "This is a very very long text for the sub title label. Testing testing the wrapping"
self.titleLabel.sizeToFit()
self.titleLabel.layoutIfNeeded()
self.subTitleLabel.sizeToFit()
self.subTitleLabel.layoutIfNeeded()
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.estimatedRowHeight = 500
self.tableView.rowHeight = UITableView.automaticDimension
}
这是解决方案的外观。如何根据内容更新单元格的高度?
【问题讨论】:
-
您是否设置了
titleLabel和 1subTitleLabel` 高度约束? ?? -
请设置标签的高度。这将解决您的问题。
标签: ios swift uitableview