9

I'm loading a custom nib file to customize the cells of a UITableView. The custom nib has a UILabel that is referenced from the main view by tag. I would like to know if it is possible to change the shadow color of the UILabel when the cell is selected to a different color so it doesn't look like in the screenshot.

screenshot

Kara
  • 6,115
  • 16
  • 50
  • 57
Iñigo Beitia
  • 6,303
  • 4
  • 40
  • 46

4 Answers4

16

I prefer to make the shadow color change inside the TableCell code to not pollute the delegate. You can override this method to handle it:

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animate
{
    UIColor * newShadow = highlighted ? [UIColor clearColor] : [UIColor whiteColor];

    nameLabel.shadowColor = newShadow;

    [super setHighlighted:highlighted animated:animate];
}
Jason
  • 1,323
  • 14
  • 19
11

You could change the label's shadow color in -tableView:willSelectRowAtIndexPath: in the delegate. For instance:

-(NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.shadowColor = [UIColor greenColor];
    return indexPath;
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.shadowColor = [UIColor redColor];
}
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 3
    This answer does not work for the highlighted cell state (i.e. if the user presses down on a cell but does not release). Jason's answer is unfortunately the best I've seen to deal with this case. It's unfortunate that it involves subclassing. You may also need to override setSelected: – Prometheus May 01 '12 at 23:17
2

I had the same issue and none of the above solutions quite worked for me - I didn't want to subclass UITableViewCell and also had some tricky selected/highlighted state changes done programmatically, which did not play well with the solutions above.

MySolution:

What I did in the end is to use a second UILabel underneath the primary UILabel to act as a shadow. For that 'shadow' UILabel you can set the 'Highlighted Color' to 'Clear Color'.

Obviously you have to update the shadow label each time you update the primary label. Not a big price to pay in many cases.

Hope that helps!

Nikolay Suvandzhiev
  • 8,465
  • 6
  • 41
  • 47
0

The simple answer, at least for the example shown above, is to not display the shadow in the first place. Since you can't see the white-on-white anyway, set the shadowColor to -clearColor.

If you actually need a shadow though, overriding the -setHighlighted method is the best solution. It keeps the code with the cell, which I think is better than trying to handle it from the table view.

Dave Batton
  • 8,795
  • 1
  • 46
  • 50