简体   繁体   中英

UITableView Cell Label Duplicating

I have a UINavigationController full of UITableViews and I use custom cells in a specific one of these.

In tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath I add a UILabel with [cell addSubview:label];

This works great, however if I then go into the detail view, then return back, it duplicates the label. How can I stop this?

Thanks.

The problem is that you are adding a new label every time the cell gets reused and displayed again.

Since you're using a custom cell already, the easiest solution would be to give the cell a UILabel property, and use that instead of adding a new label each time. Specifically, you should only add a new label if you're creating a cell instead of getting a recycled one. Or, you could add a new UILabel only if the property is nil.

Or as an alternative to adding the label in the custom class, just make sure to add the label inside the conditional cell creation. eg

UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:ident];

if(cell == nil){
   cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:ident] autorelease]; 
   [cell.contentView addSubview:[[[UILabel alloc] init] autorelease]];   // <-------
}

Add a tag to the label, then check if it exists

UILabel *label;    
if ([cell viewWithTag:2]){
    label = [cell viewWithTag:2];}
else{
    label = [[UILabel alloc]init];label.tag = 2;}

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