问题
This worked before, unless it's been so long I'm overlooking something. When the table first shows everything looks great but if I scroll up and and down labels get duplicate content.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, tableView.frame.size.width, 35)];
labelName.tag = 20;
[cell addSubview:labelName];
}
((UILabel *)[tableView viewWithTag:20]).text = [data objectAtIndex:indexPath.row];
return cell;
}
回答1:
I spotted the line that provokes it!
((UILabel *)[tableView viewWithTag:20]).text = [data objectAtIndex:indexPath.row];
You're getting the label by sending -viewWithTag:
to tableView
but you should ask the cell.
On a side note it's always better to add subviews to a cell's contentView
Here's the right implementation.
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, tableView.frame.size.width, 35)];
labelName.tag = 20;
[cell.contentView addSubview:labelName];
}
((UILabel *)[cell.contentView viewWithTag:20]).text = [data objectAtIndex:indexPath.row];
return cell;
}
回答2:
write this bellow line inside the if (cell == nil)
condition
labelName.text = [data objectAtIndex:indexPath.row];
and comment or remove this bellow line..
((UILabel *)[tableView viewWithTag:20]).text = [data objectAtIndex:indexPath.row];
来源:https://stackoverflow.com/questions/18379280/duplicate-data-when-scrolling-a-uitableview-with-custom-subviews