【问题标题】:Set table view cell height by identifier - Swift通过标识符设置表格视图单元格高度 - Swift
【发布时间】:2018-04-29 15:45:36
【问题描述】:

我正在尝试根据标识符设置表格视图中每个单元格的高度。我不想使用 indexPath.row,因为我正在从包含每种类型单元格的标志的数组中填充单元格,并且顺序是随机的。正好 3 种类型的细胞。

我使用了这段代码,但它导致了错误:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    let cell = tableV.cellForRow(at: indexPath)
    if(cell?.reuseIdentifier == "homeFeaturedR"){
        return 200
    }else{
       return 360
    }
}

错误在这一行:

let cell = tableV.cellForRow(at: indexPath)

谢谢。

【问题讨论】:

  • 您可以使用数据源数组的标志返回单元格高度!

标签: ios swift uitableview height row


【解决方案1】:

谈UITableView生命周期

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

之前调用过

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

所以我猜你的

func cellForRow(at indexPath: IndexPath) -> UITableViewCell?

返回零

【讨论】:

    【解决方案2】:

    选择tableView 时似乎您错了。您在函数heightForRowAt indexPath 中使用tableV 而不是tableView。让我们改变它,然后再试一次,即使这不是我认为的最佳方式。

    【讨论】:

      【解决方案3】:

      第一个杜克牢房

          let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
      

      然后根据需要设置单元格高度。

      【讨论】:

        【解决方案4】:

        您的heightForRowAt 方法在cellForRowAt 之前调用。这意味着在调用heightForRowAt 时,该索引路径上的单元格尚未创建。因此,您无法访问它的reuseIdentifier 或类似的东西。

        这意味着,与其试图通过查看单元格来确定要返回的高度,不如尝试使用您的模型来确定高度。

        动态表视图应该有一个数据源/模型。您的表格视图也应该有一个。看看你的cellForRowAtIndexPath 方法,在什么情况下你会使用标识符homeFeatureR 出列一个单元格?这很可能是一个 if 语句检查某些东西:

        if someCondition {
            let cell = tableView.dequeueReusableCell(withIdentifier: "homeFeatureR")!
            // set properties
            return cell
        }
        

        现在,您只需检查someCondition 是否为真,如果为真,则表示单元格的标识符必须是“homeFeatureR”,这意味着您应该返回 200。

        if someCondition {
            return 200
        } else {
            return 360
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-04-28
          • 2018-06-15
          • 1970-01-01
          • 1970-01-01
          • 2016-07-26
          • 1970-01-01
          • 2014-09-04
          相关资源
          最近更新 更多