iosswifttableviewreuseidentifier

How to detect if TableViewCell has been reused or created


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?


Solution

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