创建一个具有动态高度的 UITableView 单元格 [英] Creating a UITableView cell to have a dynamic height

查看:33
本文介绍了创建一个具有动态高度的 UITableView 单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a tableview cell to accommodate texts with varying lengths and I need each cell to have a dynamic height. I've tried using the below but no show:

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 410

有人可以帮我吗?

推荐答案

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

To set automatic dimension for row height & estimated row height, ensure following steps to make, auto dimension effective for cell/row height layout. I just tested following steps and code and works fine.

  • 分配和实现tableview数据源和委托
  • UITableViewAutomaticDimension 分配给 rowHeight &估计行高度
  • 实现委托/数据源方法(即 heightForRowAt 并返回一个值 UITableViewAutomaticDimension 给它)
  • Assign and implement tableview dataSource and delegate
  • Assign UITableViewAutomaticDimension to rowHeight & estimatedRowHeight
  • Implement delegate/dataSource methods (i.e. heightForRowAt and return a value UITableViewAutomaticDimension to it)

-

@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 中的标签实例

For label instance in UITableviewCell

  • 设置行数 = 0(& 换行模式 = 截尾)
  • 设置与其父视图/单元格容器相关的所有约束(顶部、底部、左侧).
  • 可选:设置标签的最小高度,如果你想要标签覆盖的最小垂直区域,即使没有数据.
  • Set number of lines = 0 (& line break mode = truncate tail)
  • Set all constraints (top, bottom, right left) with respect to its superview/ cell container.
  • Optional: Set minimum height for label, if you want minimum vertical area covered by label, even if there is no data.

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

Note: If you've more than one labels (UIElements) with dynamic length, which should be adjusted according to its content size: Adjust 'Content Hugging and Compression Resistance Priority` for labels which you want to expand/compress with higher priority.

这篇关于创建一个具有动态高度的 UITableView 单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆