开发者

iPhone cellForRowAtIndexPath returns cached cell

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 开发者_StackOverflow中文版my label.

Does somebody knows a way around? Ton


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.


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜