推后如何更改所选单元格的背景颜色?

时间:2013-03-05 06:40:25

标签: iphone ios ipad

我有一个应用程序,我在其中使用cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"cell_gray_with_line.png"]];更改所选单元格的颜色。但是当我在选择didselect后执行此操作时,在推送之后它不会将我的背景更改回上一个视图

if (indexPath != nil) {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];    
}   

当弹出回到此视图控制器时,我需要与正常情况相同的背景,而无需重新加载表视图。有人能帮助我吗?

5 个答案:

答案 0 :(得分:1)

您应该为UITableViewCell设置两个属性。

  1. backgroundView
  2. selectedBackgroundView
  3. 另外,您应该将cell.selectionStyle设置为UITableViewCellSelectionStyleNone

答案 1 :(得分:1)

如果将clearsSelectionOnViewWillAppear属性设置为YES,UITableViewControllers将取消选择viewWillAppear上的选定行。如果您没有使用具有该设置的表视图控制器(我认为默认为YES),请自己动手:

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

实施did(或将)取消选择委托方法并修复颜色:

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    // do what you want to the cell
}

顺便提一下,SO上的其他人建议在单元格的内容视图上设置颜色(不是cell.backgroundColor,而是cell.contentView.backgroundColor),并在willDisplayCell:forRowAtIndexPath:中进行设置。

答案 2 :(得分:0)

应该这样做,

- (void)viewDidAppear:(BOOL)animated
{
 [super viewDidAppear:animated];
 [self.tableView cellForRowAtIndexPath:[self.tableView indexPathForSelectedRow] ].backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"normal.png"]];
}

答案 3 :(得分:0)

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //First you get the cell you want to change
    UITableViewCell* theCell = [tableView cellForRowAtIndexPath:indexPath];

    //Then you change the properties (label, text, color etc..) in your case, the background color
    theCell.contentView.backgroundColor=[UIColor redColor];

    //Deselect the cell so you can see the color change

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

答案 4 :(得分:0)

与@dand相同的答案,但稍微修改一下。

- (void) viewWillAppear: (BOOL) animated
{
    [super viewWillAppear: animated];

    NSIndexPath *indexPath = [self.tableview indexPathForSelectedRow];
    [self.tableview deselectRowAtIndexPath: indexPath animated: YES];
}

并在自定义单元格实现中修改此方法。

- (void) setSelected: (BOOL) selected animated: (BOOL) animated
{
    [super setSelected: selected animated: animated];
    // Configure the view for the selected state

    if (selected)
    {
        self.backgroundColor = [UIColor redColor];
    }
    else
    {
        self.backgroundColor = [UIColor clearColor];
    }
}