按标识符设置表视图单元格高度 - Swift

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

谢谢你。

你可以使用数据源数组的标志来返回单元格高度! - dip
4个回答

6

在调用cellForRowAt方法之前,会先调用heightForRowAt方法。这意味着当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
}

1
谈论UITableView的生命周期。
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

它被称为“before”。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

因此,我猜测您的


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

返回 nil


0

看起来你在选择tableView时出错了。在heightForRowAt indexPath函数中,你使用的是tableV而不是tableView。让我们更改一下并再试一次,尽管这不是我心目中最好的方法。


-1

第一个杜克单元

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

然后根据您的喜好设置单元格高度。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接