gpt4 book ai didi

ios - 如何正确使用 UITableViewCell 和 UITableViewCellStyle 以及单元格重用?

转载 作者:搜寻专家 更新时间:2023-10-31 08:13:59 25 4
gpt4 key购买 nike

我想为默认表格单元格使用 UITableViewCellStyle.Subtitle 样式。我在 an SO answer 中找到了答案像这样:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell?
if (cell != nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
}
}

通过上面的代码,我可以成功地使用字幕单元格样式。但是,我开始觉得可能是哪里出了问题?为什么在 cell != nil 时创建一个新单元格?这样,您永远不会重复使用单元格,不是吗?此外,我可以打电话

let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")

我得到了相同的结果。为什么要使可重复使用的单元格出队然后创建一个新单元格?实现单元格重用的正确方法是什么?当时,为单元格使用 UITableViewCellStyle.Subtitle 样式?

更新

请注意第一个代码块是cell != nil,而不是cell == nil。如果我更改 cell == nil,代码将不会使用 Subtitle 样式。我认为第一个有效,因为它总是创建具有 Subtitle 样式的新单元格。

最佳答案

如果您使用的是 tableView.registerClass,则无法覆盖在创建每个单元格时传递给类的样式。我使用的解决方法是创建一个名为 SubtitleCellUITableViewCell 子类,它始终使用 .subtitle 样式。

import UIKit

class SubtitleCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
}

然后我用 tableView 注册那个类

tableView.register(SubtitleCell.self, forCellReuseIdentifier: "cell")

关于ios - 如何正确使用 UITableViewCell 和 UITableViewCellStyle 以及单元格重用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35532961/

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