Byron S
Byron S

Reputation: 109

UITableView: How to utilize cell reuse identifier?

My book is telling me that I should use a UITableView cell's reuse identifier like so

//check for reusable cell of this type
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; 

//if there isn't one, create it
if(!cell){
    cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault
                      reuseIdentifier: @"UITableViewCell"]; 
}   

So from what I see, it checks if the type of cell we want exists, and if it does, it uses it, but if it doesnt, it creates one with that desired identifier.

What if we have multiple cell styles (i.e. different reuseIdentifiers), how would we use this to create different reusable cells for us?

Upvotes: 0

Views: 4377

Answers (2)

Martin R
Martin R

Reputation: 539685

The table view manages separate queues of cells for reuse for each identifier. So for example, if the cells should have a diiferent appearance for even and odd rows (just as an example), you could do

NSString *cellIdentifier = (indexPath.row % 2 == 0 ? @"EvenCell" : @"OddCell");
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault
                      reuseIdentifier:cellIdentifier];
    if (indexPath.row % 2 == 0) {
        // set cell properties for even rows
    } else {
        // set cell properties for odd rows
    }
}

Using different reuse identifiers guarantees that a cell from an even row is not reused as a cell for an odd row.

(This example would work only if you don't insert or delete cells. Another example would be different cells depending on the content of the row.)

Upvotes: 3

Farrukh Javeid
Farrukh Javeid

Reputation: 634

indexPath, use it. It contains your row and section so whatever properties you want to set you can choose the case from row and section and set it accordingly.

Upvotes: 0

Related Questions