在使用表格视图时,可以通过以下方法实现自动高度:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 50 // 设置一个估计的行高
heightForRowAt
,返回每一行的高度:func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
titleLabel.numberOfLines = 0 // 设置标题标签可以多行显示
subtitleLabel.numberOfLines = 0 // 设置副标题标签可以多行显示
}
}
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var textView: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
textView.delegate = self
}
}
extension CustomTableViewCell: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
let sizeToFit = textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
textView.constraints.forEach { constraint in
if constraint.firstAttribute == .height {
constraint.constant = sizeToFit.height
}
}
}
}
以上是一种常见的实现自动高度的方法,可以根据实际需求进行调整和修改。
下一篇:表格视图底部有空白的问题