[英]Set table view cell height by identifier - Swift
我试图根据标识符在表格视图中设置每个单元格的高度。 我不想使用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)
谢谢。
您的heightForRowAt
方法在cellForRowAt
之前被调用。 这意味着,在调用heightForRowAt
时,尚未在该索引路径处创建单元格。 因此,您无法访问其reuseIdentifier
或类似内容。
这意味着您不应尝试通过查看单元格来确定返回的高度,而应尝试使用模型来确定高度。
动态表视图应该具有数据源/模型。 您的表格视图也应该有一个。 查看您的cellForRowAtIndexPath
方法,在什么情况下您homeFeatureR
标识符为homeFeatureR
的单元出队? 这很可能是if语句检查的内容:
if someCondition {
let cell = tableView.dequeueReusableCell(withIdentifier: "homeFeatureR")!
// set properties
return cell
}
现在,您只需检查someCondition
是否为true,如果为true,则意味着该单元格的标识符必须为“ homeFeatureR”,这意味着您应返回200。
if someCondition {
return 200
} else {
return 360
}
谈论UITableView生命周期
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
它被称为
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
所以我想你
func cellForRow(at indexPath: IndexPath) -> UITableViewCell?
返回nil
选择tableView
时,您似乎错了。 您在tableV
而不是在heightForRowAt indexPath
函数内部使用tableView
。 让我们进行更改,然后重试,即使这不是我心目中的最佳方法。
第一个duque细胞
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
之后,根据需要设置像元高度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.