How to detect if TableViewCell has been reused or created

1.7k Views Asked by At

In Swift with dequeueReusableCell API we don't have control over creating of a new instance of TableViewCell. But what if I need to pass some initial parameters to my custom cell? Setting parameters after dequeue will require a check if they have been already set and seem to be uglier than it was in Objective-C, where it was possible to create custom initializer for a cell.

Here is a code example of what I mean.

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
       }
    }
}

Do I miss something or it's how it supposed to work in Swift?

3

There are 3 best solutions below

0
Anastasia On BEST ANSWER

The working approach is basically the same as Objective-C: Do NOT register cell for "MyReuseIdentifier" and use 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
}
4
Shehata Gamal On

In swift or objective-c dequeueReusableCell will return a cell if there is an available 1 or will create another if there isn't , btw what you do in objc can be done in swift it's the same

0
A. Amini On

Always before UITVCells will reuse inside your Cell class will prepareForReuse() called. You can use this method to reset all content like imageView.image = nil.

Use the initial from UITVCell init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) to know if the cell was created.

If you want to know this infomations inside your tableView class, use func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) delegate method.

PS: Dont forget to call super.