按标识符设置 table 查看单元格高度 - Swift

Set table view cell height by identifier - Swift

我正在尝试根据标识符设置 table 视图中每个单元格的高度。我不想使用 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)

谢谢。

谈论 UITableView 生命周期

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

它在

之前被调用
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

因此我猜你的

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

returns 无

当 select tableView 时,你似乎错了。您在函数 heightForRowAt indexPath 中使用 tableV 而不是 tableView。让我们改变它,然后再试一次,即使这在我看来不是最好的方法。

第一个杜克细胞

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

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

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

这意味着您不应尝试通过查看单元格来计算 return 的高度,而应尝试使用您的模型来计算高度。

动态 table 视图应该有一个 datasource/model。您的 table 视图也应该有一个。查看您的 cellForRowAtIndexPath 方法,在什么条件下您会使用标识符 homeFeatureR 出列一个单元格?这很可能是一个 if 语句检查某些东西:

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

现在,您可以检查 someCondition 是否为真,如果为真,则意味着单元格的标识符必须是 "homeFeatureR",这意味着您应该 return 200。

if someCondition {
    return 200
} else {
    return 360
}