ios - 创建具有动态高度的 UITableView 单元格

标签 ios swift uitableview

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

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 410

有人可以帮我吗?

最佳答案

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

  • 分配和实现 TableView 数据源和委托(delegate)
  • UITableViewAutomaticDimension 分配给 rowHeight 和 estimatedRowHeight
  • 实现委托(delegate)/数据源方法(即 heightForRowAt 并向其返回值 UITableViewAutomaticDimension)

-

@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
}

对于 UITableviewCell 中的标签实例

  • 设置行数=0(&换行模式=截尾)
  • 设置关于其父 View /单元格容器的所有约束(顶部、底部、左右)。
  • 可选:设置标签的最小高度,如果您希望标签覆盖的最小垂直区域,即使没有数据也是如此。

enter image description here

注意:如果您有多个具有动态长度的标签(UIElements),应根据其内容大小进行调整:为您选择的标签调整“Content Hugging and Compression Resistance Priority”想要以更高的优先级展开/压缩。

关于ios - 创建具有动态高度的 UITableView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48585335/

相关文章:

swift - 如何在 swift 中使用 removeObjectsInArray

ios - 如何动态调整自定义单元格高度

iOS UITableViewController静态tableView不滚动

iphone - iOS - 如何使用用户名和密码获取 twitter OAuthtoken

ios - Swift:将照片图像加载到应用程序中

ios - UICollectionView cellForItemAtIndexPath 滚动后返回 nil

swift - 滚动整个屏幕而不仅仅是桌面 View

ios - 如何从位于自定义 UITableView 中的 UITextField 读取数据

ios - 找到ViewController中初始化了哪个StoryBoard? Xcode

iphone - 如何在尝试实现我的 DBAccess 类时修复 sqlite3 错误