在带有dequeueReusableCell API的Swift中,我们无法控制创建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中,dequeueReusableCell
如果有一个可用的1,将返回一个单元格;如果没有,则将创建另一个单元,但在objc中所做的操作可以迅速完成,这是相同的。>>
总是在UITVCells将在Cell类内部重用之前,将调用prepareForReuse()
。您可以使用此方法重设所有内容,例如imageView.image = nil
。