【发布时间】:2018-08-29 08:40:37
【问题描述】:
在阅读 Ray Wenderlich guide 的“Self-sizing Table View Cells”以及 this question 并回答之后,我决定向大家寻求帮助。
有一个以编程方式创建的单元格:
import UIKit
class NotesCell: UITableViewCell {
lazy private var cellCaption: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.medium)
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
return label
}()
func configure(with note: NotesModel) {
cellCaption.text = note.name
contentView.addSubview(cellCaption)
}
override func layoutSubviews() {
super.layoutSubviews()
NSLayoutConstraint.activate([
cellCaption.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
cellCaption.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8),
cellCaption.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8),
// cellCaption.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),
cellCaption.bottomAnchor.constraint(greaterThanOrEqualTo: contentView.bottomAnchor, constant: -8)
])
// cellCaption.sizeToFit()
// cellCaption.layoutIfNeeded()
}
}
表格视图控制器在委托方法中使用 UITableViewAutomaticDimension:
extension NotesTableViewController {
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
}
因此,最长的标题被完全指示,但单元格的高度与所有其他单元格的高度相同。
一些更新!
我已经尝试将以下代码放入 viewDidLoad() 中:
tableView.rowHeight = 44
tableView.estimatedRowHeight = UITableViewAutomaticDimension
启用委托方法并同时禁用它们。结果是一样的:(
【问题讨论】:
-
在 viewDidLoad() 中试试这个:
tableView.estimatedRowHeight = 50 -
我认为附上的截图来自模拟器,请在真机上查看。
-
很遗憾,在真机上结果也是一样的
标签: ios swift uitableview uitableviewautomaticdimension