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

问题描述 投票:1回答:2

在带有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中工作?

ios swift tableview reuseidentifier
2个回答
0
投票

在swift或Objective-c中,dequeueReusableCell如果有一个可用的1,将返回一个单元格;如果没有,则将创建另一个单元,但在objc中所做的操作可以迅速完成,这是相同的。>>


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.