Question

Alrighty so basically I have a tableView that is filled within the ".plist" with items.

The tableView then gets its functionality from this code:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) { 
//do something
}

if (indexPath.row == 1) { 
//do something
}

However I'd like the item or the text within the tableView to change color when it's pressed and when it's released it should go back to its original color.

I then added this code to change the background color as I couldn't find anything to just change the text:

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.font=[UIFont fontWithName:@"Helvetica" size:22.0];
    cell.contentView.backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];

But then the problem is that it remains with this background color.

I then tried to create a deselect method like this:

-(void)tableView:(UITableView *)tableView deSelectRowAtIndexPath:(NSIndexPath *)indexPath{

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.font=[UIFont fontWithName:@"Helvetica" size:22.0];
cell.contentView.backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:1.0 alpha:2.0];

}

However this does not change the color again.

So basically I either want to the background color or the text color to change when it's being pressed but then change back to the original color when it's released. Pretty much like how a UIButton works when it's pressed.

Was it helpful?

Solution

The correct way to do is set the selectedBackgroundView and backgroundView to the cell.

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  UITableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
  if(!cell){
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"];
    UIView * selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    selectedBackgroundView.backgrounColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
    cell.selectedBackgroundView = selectedBackgroundView
   }

  return cell;
}

This way you dont have to set the background color when the selection is done and change the color back when deselected.

If you would like to change the text properties based on selection, sub class UITableViewCell and override setSelected:animated method.

- (void)setSelected:(BOOL)selected animated:(BOOL)animated{
 [super setSelected:selected animated:animated];
 self.textLabel.titleColor.textColor = selected ? selectedColor : notSelectedColor;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top