gpt4 book ai didi

ios - 如何以编程方式初始化/使用带有 CellStyle = .value1 的 UITableViewCells?

转载 作者:行者123 更新时间:2023-11-29 05:31:18 24 4
gpt4 key购买 nike

我想使用Apple给定的单元格样式value1对于我的细胞,我不确定这是如何正确完成的。设置单元格样式的唯一可能的方法是在Cell's initialization期间。 ,但我认为在这种情况下子类化是不必要的。

设置 CellType 的正确方法是什么?我尝试在 tableView(_:cellForRowAt:) 中完成它,但是 dequeueReusableCell(withIdentifier:for:) 不返回可选,这就是为什么我的逻辑无法工作.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCellIdentifier", for: indexPath)

if cell == nil {
cell = UITableViewCell.init(style: .value1, reuseIdentifier: "myCellIdentifier")
}

// setup cell text and so on
// ...

return cell
}

最佳答案

不要调用tableView.register(...)

相反,请在 cellForRowAt 中使用此方法:

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

// try to dequeue a cell
var cv1 = tableView.dequeueReusableCell(withIdentifier: "cv1")

// if that fails, create a new one
if cv1 == nil {
cv1 = UITableViewCell(style: UITableViewCell.CellStyle.value1, reuseIdentifier: "cv1")
}

// just for sanity
guard let cell = cv1 else { fatalError("Failed to get a cell!") }

// set the cell properties as desired
cell.contentView.backgroundColor = .yellow
cell.detailTextLabel?.text = "Row \(indexPath.row)"
return cell

}

关于ios - 如何以编程方式初始化/使用带有 CellStyle = .value1 的 UITableViewCells?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57527066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com