简体   繁体   中英

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

I'm adding items (eg 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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM