UITableView Cell行高自动适应内容长度的实现

在iOS开发中,UITableView 是一个常用的组件,用来展示列表数据。然而,默认的行高可能无法适应多行文本的显示,导致文本被裁剪或显示不完全。为了解决这个问题,我们可以根据每行的文本内容动态调整行高。首先,我们需要关注两个关键的 UILabel 属性:

  1. numberOfLines:设置为0,允许UILabel自动换行。
  2. lineBreakMode:设置为 UILineBreakModeWordWrap,确保换行时不会在单词中间。

接下来,我们可以使用 sizeWithFont:constrainedToSize:lineBreakMode: 方法来计算文本所需的高度。例如:

let font = UIFont.systemFont(ofSize: 14.0)
let contentLabelWidth = ... //实际label宽度
let maxSize = CGSize(width: contentLabelWidth, height: 1500) // 最大高度
let size = dataString.size(withAttributes: [.font: font]).constrained(to: maxSize).size

UITableView 的代理方法 tableView:heightForRowAtIndexPath: 中使用计算出的高度来设置行高:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
   let font = UIFont.systemFont(ofSize: 14.0)
   let contentLabelWidth = ... //实际label宽度
   let maxSize = CGSize(width: contentLabelWidth, height: 1000) // 最大高度
   let size = dataString[indexPath.row].size(withAttributes: [.font: font]).constrained(to: maxSize).size
   return size.height + 5 // 5是上下间距
}

为了优化性能,可以考虑使用 NSCache 缓存计算结果,或者在 iOS 8 及以上版本使用 estimatedRowHeightrowHeight 属性进行预估,以提高滚动流畅性。

doc 文件大小:12.5KB