Changing color of UITableViewCell on state pressed and state selected

匆匆过客 提交于 2019-12-06 09:31:57

If you want gray then

cell.selectionStyle=UITableViewCellSelectionStyleGray;  

Or you can set background color on didSelectRow

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView reloadData];
    UITableViewCell *cell=(UITableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    [cell setBackgroundColor:[UIColor orangeColor]];
}  

If you don't want to reload tableData then you have to save your previousSelected Index value then

- (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;
}

Write these two method in your Custom Cell

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

}

A pretty elegant solution is to override the setHighlighted: method of your tableViewCells.

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

UITableView will automatically set the selected cell highlighted @property to YES when the user tap on the cell.

Don't forget to call [_tableView deselectCellAtIndexPath:indexPath animated:NO]; in your didSelect tableView delegate method if you want to make your cell unselected!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!