How to determine if the cell returned by dequeueReusableCellWithIdentifier will be reused in iOS 6?

I am adding elements (e.g. gesture recognizers, subviews) to cells in cellForRowIndexPath. I don't want to add them if the cell is reused (presumably), so is there a way to easily tell if the cell is new or reused?

The cell prototype is defined in the storyboard.

I do not use a custom subclass for the cell (it seems redundant). I use a cell tag to identify subviews, so I cannot use this.

I could use the pre-iOS 6 approach, but of course, the best way to make something so simple?

I could not find anything on the Internet, so I'm afraid I can embarrass something, but it's hard to find.

+5
source share
2 answers

The easiest way to handle this is to check for the things you need to add.

So, let your cell should have a subzone with tag 42, if it is 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;
}
+7
source

This is probably an excess compared to using the pre-iOS6 approach (without a registered class), but if you really want to stick with this, you can use related 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 verified)

+1
source

All Articles