views:

435

answers:

5

Hi,

When i add a label to a cell using:

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell addSubView:someLabel];
}

It adds the label to multple cells, because it adds the label to a cached cell. So every cell in the tableView thats uses a cached cell, will display my label.

Does somebody knows a way around? Ton

A: 

You'll need to keep track of whether or not each cell has the label currently applied. In cellForRowAtIndexPath: check if it should be there, if so then add it if necessary, else remove it if necessary.

David Kanarek
thanks for your answer, but why should i do that? when new cells get in to the display it rebuilds the cell so my label shouldn't even be their. I only want my label to exist if the user tabs the accessory button, when the cell goes off the view, it should go away because it will rebuild the cell.
Ton
So you're using the same cell in multiple places, but you want to change only one instance? Your best bet is probably to copy the reference cell and add the label, then switch between those two as necessary.
David Kanarek
+1  A: 

If your cell is a subclass of UITableViewCell, you can override - (void)prepareForReuse which gets called just before the cell is returned from - (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier

This is the way to provide a 'clean slate' for your cells, but only the cached ones that are about to be reused.

moshy
+2  A: 

Give unique identifier name like:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

    static NSString *CellIdentifier = NSLocalizedString(@"Cell",@"");
…
}

instead of giving constatnt identifier name, give your own unique identifier name like:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

    static NSString *CellIdentifier = [self getuniqueID];
...
}

This will solve your problem.

Manjunath
Sure, but you lose out on scrolling performance. This may be fine for a small table, but if there are hundreds of rows...
moshy
+1  A: 

Why not just simplify things and just hide the label by default and include it on all the cells.

When you tap the cell, then instead of adding a view - just show the one that is there but hidden.

When you are done, hide the label.

sylvanaar
A: 

I sometimes use this code: (When the cell != nil)

NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
for (UIView *subview in subviews) {
    [subview removeFromSuperview];
}
[subviews release];

It removes all subviews of an cached cell. Dont know if it is a performance hog, but I havent hade any problems.

Olof