Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if a cell returned by dequeueReusableCellWithIdentifier is being reused in iOS 6?

I'm adding items (e.g. gesture recognizers, subviews) to cells in cellForRowIndexPath. I don't want to add these if the cell is being reused (presumably) so is there a way of easily telling if the cell is new, or is being reused?

The cell prototype is defined in a storyboard.

I'm not using a custom subclass for the cell (seems like overkill). I'm using the cell tag to identify subviews, so can't use that.

I could use the pre-iOS 6 approach, but surely there's a better way to do something so simple?

I couldn't find anything online, so afraid I may be confused about something - but it's a hard thing to search for.

like image 448
dommer Avatar asked Feb 15 '13 19:02

dommer


2 Answers

The simplest way to tackle this is to check for the existence of the things you need to add.

So let's say your cell needs to have a subview with the tag 42 if it's not already present.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    UIView *subview = [cell viewWithTag:42];
    if (!subview) {
       ... Set up the new cell
    }
    else {
       ... Reuse the cell
    }
    return cell;
}
like image 119
AlleyGator Avatar answered Sep 30 '22 07:09

AlleyGator


It's probably overkill compared to using the pre-iOS6 (no registered class) approach, but if you really want to stick with that, you can use associated objects.

#import <objc/objc-runtime.h>

static char cellCustomized;

...
-(UITableViewCell *)getCell
{
    UITableViewCell *cell = [tableView dequeueReusableCellForIdentifier:myCell];
    if(!objc_getAssociatedProperty(cell, &cellCustomized)) {
        [self setupCell:cell];
        objc_setAssociatedProperty(cell, &cellCustomized, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return cell;
}

...

(not tested)

like image 35
Kevin Avatar answered Sep 30 '22 09:09

Kevin