在按下状态和选择状态时更改UITableViewCell的颜色

时间:2013-03-04 10:43:50

标签: iphone uitableview android-selector

我正在使用带有customCell的UITableView(CustomCell有2个标签和一个ImageView)。

在正常模式下,我需要所有细胞的白色。

如果用户按下特定单元格,则该单元格的颜色应为灰色(其余单元格应为白色)

如果用户释放相同的单元格,该单元格的颜色应为橙色(其余单元格应为白色)

我怎么能搞清楚?

我已经尝试过使用setSelectedBackground,willSelectRowAtIndexPath和Gestures方法。但无法看到同一Cell的这3种颜色状态。两个州中的任何一个都在一起工作。

任何想法我如何实现相同的功能?

我使用选择器在android中实现了相同的功能。我想在iPhone中使用相同的功能。任何帮助?

提前致谢!

3 个答案:

答案 0 :(得分:7)

将这两种方法写入自定义单元格

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    self.contentView.backgroundColor=[UIColor greenColor];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    self.contentView.backgroundColor=[UIColor orangeColor];

}

答案 1 :(得分:3)

如果你想要灰色那么

cell.selectionStyle=UITableViewCellSelectionStyleGray;  

或者您可以在didSelectRow

上设置背景颜色
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView reloadData];
    UITableViewCell *cell=(UITableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    [cell setBackgroundColor:[UIColor orangeColor]];
}  

如果您不想重新加载tableData,则必须保存之前选择的索引值

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Make oreange cell
    UITableViewCell *presentCell=(UITableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    [presentCell setBackgroundColor:[UIColor orangeColor]];

    //make your previous cellBackgrod to clear, you can make it white as per your requirement
    UITableViewCell *previouscell=(UITableViewCell*)[tableView cellForRowAtIndexPath:previousSelectedCellIndexPath];
    [previouscell setBackgroundColor:[UIColor clearColor]];

    //save your selected cell index
    previousSelectedCellIndexPath=indexPath;
}

答案 2 :(得分:3)

一个非常优雅的解决方案是覆盖tableViewCells的setHighlighted:方法。

- (void)setHighlighted:(BOOL)highlighted {
  [super setHighlighted:highlighted];
  if(highlighted) {
    _backView.backgroundColor = [UIColor blueColor];
  }
  else
  {
    _backView.backgroundColor = [UIColor blackColor];
  }
}

当用户点击单元格时,UITableView会自动将所选单元格highlighted @property设置为YES。

如果要取消选择单元格,请不要忘记在didSelect tableView委托方法中调用[_tableView deselectCellAtIndexPath:indexPath animated:NO];

相关问题