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

标签 ios objective-c swift uitableview

我想为默认表格单元格使用 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/

相关文章:

ios - 在应用程序的新更新中添加 CoreData 的问题

ios - Objective-C 如何检查哪些对象正在引用我的对象(保留周期)

iphone - 如果 UITableview 为空显示图像

swift - 添加自定义 NSViewController 用 Nib 进行查看

ios - Swift segue 不会将数据传递给旧的 ViewController

ios - 确定哪个 segue 触发了 UIViewController

ios - 展开两个 segue

c++ - 在独立的 Xcode playground 中运行 c 或 c++ 代码

ios - 使用 Core Location 在 Apple Watch 上获得精确的室内位置更新?

iphone - "vector-based-data"解决方案比 "tile-based-data"解决方案复杂多少?