如何正确使用 UITableViewCell 和 UITableViewCellStyle 并正确重用单元格? [英] How to use UITableViewCell with UITableViewCellStyle with cell reuse correctly?
问题描述
我想对默认表格单元格使用 UITableViewCellStyle.Subtitle
样式.我在 一个 SO 答案 中找到了这样的答案:
I want to use UITableViewCellStyle.Subtitle
style for the default table cells. I found an answer in an SO answer like this:
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
时为什么要创建一个新单元格?通过这种方式,您永远不会重复使用单元格,不是吗?此外,我可以打电话给
With the code above, I can successfully use the Subtitle cell style. However, I start to think something might be wrong? Why create a new cell when cell != nil
? In this way, you never reuse cells, isn't it? Besides, I can just call
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
我也有同样的结果.为什么要出列可重用的单元格&然后创建一个新的?实现单元重用的正确方法是什么?当时,要为单元格使用 UITableViewCellStyle.Subtitle
样式?
I am having the same result. Why dequeue reusable cell & then create a new one? What is the right way to achieve cell reuse & at the time, to use UITableViewCellStyle.Subtitle
style for the cells?
更新
请注意第一块代码是cell != nil
,而不是cell == nil
.如果我更改 cell == nil
,代码将不会使用 Subtitle
样式.我认为第一个有效,因为它总是以 Subtitle
样式创建新单元格.
Please note the first block of code is cell != nil
, not cell == nil
. If I change cell == nil
, the code will not use the Subtitle
style. I think the first works because it always create new cells with Subtitle
style.
推荐答案
如果您正在使用 tableView.registerClass
,则无法覆盖在每个单元格被创建.我使用的一种解决方法是创建一个名为 SubtitleCell
的 UITableViewCell
子类,该子类始终使用 .subtitle
样式.
If you're using tableView.registerClass
, there is no way to override the style that it will pass to the class when each cell is created. A workaround I've used is to create a UITableViewCell
subclass called SubtitleCell
that always uses the .subtitle
style.
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")
这篇关于如何正确使用 UITableViewCell 和 UITableViewCellStyle 并正确重用单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!