【问题标题】:How to use UITableViewCell with UITableViewCellStyle with cell reuse correctly?如何正确使用 UITableViewCell 和 UITableViewCellStyle 以及单元重用?
【发布时间】:2016-06-02 15:48:29
【问题描述】:

我想为默认表格单元格使用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 样式的新单元格。

【问题讨论】:

  • 我认为你是正确的,它不会重复使用单元格。如果将其更改为 cell == nil 会发生什么。
  • 如果我更改cell == nil,则单元格不使用UITableViewCellStyle.Subtitle 样式
  • 你在用你的tableview注册一个笔尖/类吗?故事板中有原型单元吗?
  • 我没有单元格的笔尖/类。我是这样注册的tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell"),也许是在某个地方设置样式?

标签: ios objective-c swift uitableview


【解决方案1】:

如果您使用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")

【讨论】:

  • hm...这很有趣...我认为同时设置样式和单元格结果的答案实际上是错误的。它只是创建新的单元格。
【解决方案2】:

你基本上是对的;您不需要代码的第二部分。

这个:

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

如果没有可重复使用的单元格,将给你一个“新”单元格,否则会给你一个现有的单元格。

【讨论】:

  • 你确定吗?我认为这将始终创建一个新单元格。这里的重用标识符只供 UITableView.dequeueReusableCell 以后使用。仔细想想,也不对,这里没有引用table view对象
猜你喜欢
  • 1970-01-01
  • 2010-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 1970-01-01
相关资源
最近更新 更多