如何将 UITableViewCell 与 UITableViewCellStyle 一起使用并正确重用单元格?

2024-04-23

我想用UITableViewCellStyle.Subtitle默认表格单元格的样式。我在中找到了答案一个如此的答案 https://stackoverflow.com/questions/24062285/how-to-set-uitableviewcellstylesubtitle-and-dequeuereusablecell-in-swift像这样:

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单元格的样式?

UPDATE

请注意第一块代码是cell != nil, not cell == nil。如果我改变cell == nil,代码不会使用Subtitle风格。我认为第一个有效,因为它总是创建新的单元格Subtitle style.


如果您正在使用tableView.registerClass,无法覆盖创建每个单元格时传递给类的样式。我使用的解决方法是创建一个UITableViewCell子类称为SubtitleCell总是使用.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")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 UITableViewCell 与 UITableViewCellStyle 一起使用并正确重用单元格? 的相关文章

随机推荐