Reputation: 19820
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.
Upvotes: 6
Views: 1910
Reputation: 1276
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;
}
Upvotes: 7
Reputation: 56129
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)
Upvotes: 1