我尝试将UITableView.automaticDimension既用于heightForRowAt,又用于估计的HeightFortowRowAt,单元格的相同结果不会随着视图的动态变化而改变。
以下是一些相关代码:
从视图控制器中:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// return getSize(large: 70, medium: 60, small: 50)
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
在表格视图单元格中:
func setup(_ lineItem: MenuItem) {
contentView.backgroundColor = .white
configureTransactionView(lineItem)
configureItemNameLabel(lineItem)
configurePriceLabel(lineItem)
configureSizeLabel(lineItem)
}
private func configureTransactionView(_ lineItem: MenuItem) {
itemView = UIView()
guard let itemView = itemView else { return }
itemView.clipsToBounds = true
itemView.layer.cornerRadius = 5
itemView.layer.borderColor = UIColor.lightGray.cgColor
itemView.layer.borderWidth = 0.5
itemView.backgroundColor = .white
contentView.addSubview(itemView)
itemView.translatesAutoresizingMaskIntoConstraints = false
itemView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
itemView.widthAnchor.constraint(equalTo: contentView.widthAnchor, multiplier: 0.8).isActive = true
itemView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4).isActive = true
let fontSize = getSize(large: 14, medium: 13.5, small: 12)
guard let topFont = UIFont(name: AppFont.secondary.name, size: fontSize) else { return }
let heightForTopLabel = heightForView(text: lineItem.name, font: topFont, width: 195)
var text = ""
if lineItem.quantity > 1 && lineItem.toppings != nil {
text = generateTextWithMultipleSelected(lineItem)
} else if lineItem.quantity > 1 {
if lineItem.size != nil {
guard let size = lineItem.size else { return }
text = "\(size) | Quantity: \(lineItem.quantity)"
} else {
text = "Quantity: \(lineItem.quantity)"
}
} else if lineItem.toppings != nil {
text = generateTextWithSingleSelected(lineItem)
} else {
if lineItem.size != nil {
guard let size = lineItem.size else { return }
text = "\(size)"
} else {
text = ""
}
}
let bottomFontSize = getSize(large: 11, medium: 10.5, small: 9.5)
guard let font = UIFont(name: AppFont.secondary.name, size: bottomFontSize) else { return }
let heightForBottomLabel = heightForView(text: text, font: font, width: 200)
let height = heightForTopLabel + heightForBottomLabel + 10
itemView.heightAnchor.constraint(equalToConstant: height).isActive = true
}
答案 0 :(得分:0)
在您的TableViewController viewDidLoad()中添加以下内容:
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 600 //change according to your needs
还删除heightForRowAtIndexPath和estimetedHeightForRowAtIndexPath方法。
这是一个很好的教程: https://www.raywenderlich.com/8549-self-sizing-table-view-cells