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.

dommer
  • 19,610
  • 14
  • 75
  • 137
  • 1
    You're not confused, it does mess up the pattern a bit. – jrturton Feb 15 '13 at 20:28
  • @jrturton. Thanks. I was beginning to doubt myself. – dommer Feb 15 '13 at 20:32
  • 2
    If you don't want to add things if the cell is being reused, that implies (I think) that you're not changing what you're adding in a dynamic way, so why not add these things in IB to start with? – rdelmar Feb 15 '13 at 20:32
  • @rdelmar. I'm doing things adding some third party controls and customizing swipe gestures to distinguish left and right swipes. It might be possible to do all these things in Storyboards, but my knowledge of them hasn't reached that stage yet if it is. – dommer Feb 15 '13 at 20:35

2 Answers2

7

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;
}
AlleyGator
  • 1,266
  • 9
  • 13
1

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)

Community
  • 1
  • 1
Kevin
  • 53,822
  • 15
  • 101
  • 132