【问题标题】:Some tableview cells with dynamic height, other with fixed height一些具有动态高度的表格视图单元格,其他具有固定高度的表格视图单元格
【发布时间】:2018-05-06 17:03:47
【问题描述】:

我有一个表格视图。我想要一些具有动态高度的表格视图单元格,而其他具有固定高度的单元格。对于动态高度,我在 viewDidLoad 视图控制器委托中使用了以下几行。

tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension

在一个表格视图中固定高度单元格和自定大小单元格的有效方法是什么?

提前致谢。

【问题讨论】:

    标签: ios swift uitableview tableview row-height


    【解决方案1】:

    斯威夫特 3

    您可以通过这样做在表格视图中重新运行动态和静态单元格高度

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    
        if indexPath.row == 0 {
            return 120.0 // for static cell height
        }
        else {
            return UITableViewAutomaticDimension // for dynamic cell height
        }
    }
    

    你必须像这样实现另一个 tableview estimatedHeightForRowAt 方法

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    
        if indexPath.row == 0 {
            return 120.0
        }
        else {
            return UITableViewAutomaticDimension
        }
    }
    

    不要忘记将标签 lineNumbers 设置为 0 和 lineBreakMode 哪个标签将动态扩展,最重要的是不要将标签高度设置为固定。

    【讨论】:

    • 是否必须实现委托方法“estimatedHeightForRowAt”?
    • 首先我尝试不使用它,结果不是我所期望的。我的意思是细胞高度根本没有扩大。之后我尝试了它并得到了我想要的预期结果。我遇到了同样的问题,我用这种方式解决了。
    • 它的反应太迟了。你找到更好的解决方案了吗?如果您有,请随时分享。
    • 好的,感谢您的回复!我会试一试,然后告诉你:)
    【解决方案2】:

    斯威夫特 4

    您可以使用此函数中的indexPath 为某些行返回固定高度,为其他行返回动态高度。

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

    【讨论】:

    • Swift 5 UITableView.automaticDimension
    【解决方案3】:

    假设indexPath.row = 0和1分别包含静态高度和动态高度,那么

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
    {
         if indexPath.row == 0 {
            return 120
         } else {
            return UITableViewAutomaticDimension
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      • 2015-04-16
      相关资源
      最近更新 更多