阅读了Ray Wenderlich的“自适应表视图单元格”指南以及这个问题和其中的答案后,我决定向大家寻求帮助。
有一个通过编程创建的单元格:
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
开启委托方法和禁用委托方法的结果是一样的 :(
tableView.estimatedRowHeight = 50
- Ali Moazenzadeh