滚动时uitableview单元格背面颜色问题

时间:2014-03-11 13:22:40

标签: iphone uitableview

我有一个像这样的行的可用视图单元格:

if (!cell) {
    UIViewController *controller = [[UIViewController alloc] initWithNibName:@"OpenOrdersCell" bundle:nil];
    cell = (OpenOrdersCell *)controller.view;

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.contentView.clipsToBounds = YES;
    [cell setBackgroundColor:[UIColor colorWithRed:238.0f/255.0f green:238.0f/255.0f blue:238.0f/255.0f alpha:1.0f]];

}...

这样运行正常,没有任何问题,即使在向上和向下滚动多次,代码仍然是statle。 现在在didSelect行委托方法中我想改变行的背景颜色。我也在此成功。但是当我在下面滚动时,单元格背面颜色变为选定颜色。

这是didSelect中的代码:

[tableView beginUpdates];
OpenOrdersCell *cell = (OpenOrdersCell *)[tableView cellForRowAtIndexPath:indexPath];

NSLog(@"row is %d section is %d cell.orderIdLabel.text is %@",indexPath.row, indexPath.section, cell.orderIdLabel.text);
[self reStructureCellForIndexPath:indexPath andCell:cell];
[tableView endUpdates];

这是重组:

if ([cell viewWithTag:TAG_EXPANDED_CELL_VIEW]) {


    [cell setBackgroundColor:[UIColor colorWithRed:238.0f/255.0f green:238.0f/255.0f blue:238.0f/255.0f alpha:1.0f]];//default bg

    return;
}
cell.backgroundColor = [UIColor colorWithRed:195.0f/255.0f green:199.0f/255.0f blue:202.0f/255.0f alpha:1.0f];//selected bg

the expanded view with selected id 166

enter image description here

[我在下面滚动你可以看到单元格如果148被选中后选择背景颜色?这是问题]

enter image description here

1 个答案:

答案 0 :(得分:0)

您正在重复使用所选单元格而您没有重置背景颜色......

if (!cell) {
    UIViewController *controller = [[UIViewController alloc] initWithNibName:@"OpenOrdersCell" bundle:nil];
    cell = (OpenOrdersCell *)controller.view;

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.contentView.clipsToBounds = YES;
[cell setBackgroundColor:[UIColor colorWithRed:238.0f/255.0f green:238.0f/255.0f blue  :238.0f/255.0f alpha:1.0f]];

}...

在这里,您需要确定单元格是否为选定单元格并相应地设置背景...

if (!cell) {
    UIViewController *controller = [[UIViewController alloc] initWithNibName:@"OpenOrdersCell" bundle:nil];
    cell = (OpenOrdersCell *)controller.view;

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.contentView.clipsToBounds = YES;

}...

//

if(indexPath.Row == savedSelectedRow) {
    cell.backgroundColor = [UIColor colorWithRed:195.0f/255.0f green:199.0f/255.0f blue:202.0f/255.0f alpha:1.0f];//selected bg
} else {
    cell.backgroundColor = [UIColor colorWithRed:238.0f/255.0f green:238.0f/255.0f blue  :238.0f/255.0f alpha:1.0f];
}

didSelect中,您可以将indexPath.Row存储在名为savedSelectedRow的变量中,以便日后检查