在Swift的dequeueReusableCell API中,我们无法控制创建一个新的TableViewCell实例。但是如果我需要向我的自定义单元格传递一些初始参数呢?在dequeue之后设置参数将需要检查它们是否已经被设置,并且看起来比在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 中 dequeueReusableCell
如果有一个可用的1,将返回一个单元格,如果没有,将创建另一个单元格,顺便说一下,你在objc中做的事情可以在swift中完成,这是一样的。
总是在UITVCells之前将你的Cell类里面的重用将 prepareForReuse()
调用。你可以使用这个方法来重置所有的内容,就像使用 imageView.image = nil
.
使用UITVCell的首字母 init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)
来知道该单元格是否被创建。
如果你想在你的tableView类中知道这些信息,可以使用 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
委托方法。
PS: 不要忘记调用 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
}