1

I want to change the selected cell background color and keep the text on that cell. Then I did like this, it can change the cell color but the text on the cell will disappear.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MessageCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    cell.textLabel.text = [self.receivedData objectAtIndex:indexPath.row];

    return cell;
}

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

    static NSString *CellIdentifier = @"MessageCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    UIView *bgColorView = [[UIView alloc]init];
    bgColorView.backgroundColor = [UIColor colorWithRed:0.529 green:0.808 blue:0.922 alpha:0.5];

    cell.selectedBackgroundView = bgColorView;

}
jww
  • 97,681
  • 90
  • 411
  • 885
Peter
  • 13
  • 3
  • What color is the text? – Chris Oct 11 '14 at 18:58
  • Possible duplicate of [Changing background color of selected cell?](http://stackoverflow.com/questions/2418189/iphone-uitableviewcell-changing-background-color-of-selected-cell) – jww Oct 11 '14 at 19:42
  • You shouldn't be dequeuing a new cell. Get a reference to the cell you selected using the table view method, cellForRowAtIndexPath:. – rdelmar Oct 11 '14 at 19:50

1 Answers1

0

You are replacing the current view (the one that has got your text in it) with a new instance of UIView (with no text in it, but your new color). That is why your text is disappearing. You should change the background color property of selectedBackgroundview like so:

cell.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:0.529 green:0.808 blue:0.922 alpha:0.5];

Although I think you can even ditch the selectedBackgroundView part and just do cell.backgroundColor = ... in didSelectRowAtIndexPath

Chris
  • 7,830
  • 6
  • 38
  • 72