创建一个具有动态高度的 UITableView 单元格

Ish*_*ael 4 uitableview ios swift

我正在尝试创建一个 tableview 单元格以容纳不同长度的文本,并且我需要每个单元格都具有动态高度。我试过使用以下但没有显示:

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 410
Run Code Online (Sandbox Code Playgroud)

有人可以帮我吗?

Kru*_*nal 10

要为行高和估计行高设置自动尺寸,请确保按照以下步骤使自动尺寸对单元格/行高布局有效。我刚刚测试了以下步骤和代码并且工作正常。

  • 分配和实现 tableview 数据源和委托
  • 分配UITableViewAutomaticDimension给 rowHeight 和estimatedRowHeight
  • 实现委托/数据源方法(即heightForRowAtUITableViewAutomaticDimension为其返回值)

——

@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Don't forget to set dataSource and delegate for table
    table.dataSource = self
    table.delegate = self

    // Set automatic dimensions for row height
    table.rowHeight = UITableViewAutomaticDimension
    table.estimatedRowHeight = UITableViewAutomaticDimension
}



// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
Run Code Online (Sandbox Code Playgroud)

对于 UITableviewCell 中的标签实例

  • 设置行数 = 0(& 换行模式 = 截尾)
  • 设置与其父视图/单元格容器相关的所有约束(顶部、底部、左侧)。
  • 可选:设置标签的最小高度,如果你想要标签覆盖的最小垂直区域,即使没有数据。

在此处输入图片说明

注意:如果您有多个具有动态长度的标签(UIElements),应根据其内容大小进行调整:为您希望以更高优先级展开/压缩的标签调整“内容拥抱和压缩阻力优先级”。