如何检测TableViewCell是否已被重用或创建



在Swift中,使用dequeueReusableCell API,我们无法控制创建TableViewCell的新实例。但是,如果我需要将一些初始参数传递给我的自定义单元格,该怎么办?在出列后设置参数将需要检查它们是否已经设置,并且似乎比Objective-C中的参数更丑陋,在Objective-C可以为单元格创建自定义初始值设定项。

以下是我的意思的代码示例。

Objective-C, assuming that I don't register a class for the specified identifier:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* reuseIdentifier = @"MyReuseIdentifier";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if (!cell)
{
cell = [[MyTableViewCell alloc] initWithCustomParameters:...]; // pass my parameters here
}
return cell;
}
Swift:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyReuseIdentifier")
if let cell = cell as? MyTableViewCell {
// set my initial parameters here
if (cell.customProperty == nil) {
cell.customProperty = customValue
}
}
}

我是错过了什么,还是Swift应该这样做?

在swift或objective-c中,如果有可用的1,dequeueReusableCell将返回一个单元格,如果没有,则将创建另一个单元格

UITVCells在Cell类中重用之前,总是会调用prepareForReuse()。您可以使用此方法重置所有内容,如imageView.image = nil

使用UITVCellinit(style: UITableViewCell.CellStyle, reuseIdentifier: String?)中的首字母来了解该单元格是否已创建。

如果您想知道tableView类中的这些信息,请使用func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)委托方法。

附言:别忘了打super.

工作方法与Objective-C基本相同:不要为"MyReuseIdentifier"注册单元格,并使用dequeueReusableCell(withIdentifier:(

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "MyReuseIdentifier")
if cell == nil {
cell = MyTableViewCell.initWithCustomParameters(...)
}
return cell
}

最新更新