Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

iphone - Removing text shadow in UITableViewCell when it's selected

I've added a text shadow to cells in my UITableView to give them an etched look:

cell.textLabel.textColor = [UIColor colorWithWhite:0.2 alpha:1.000];
cell.textLabel.shadowColor = [UIColor whiteColor];
cell.textLabel.shadowOffset = CGSizeMake(0, 1);

Since the shadow color is actually white, when a row gets selected and becomes blue, the white shadow becomes really visible and makes the text look ugly.

Does anyone know how I can remove the shadow before the default cell selection style gets applied?

I have tried:

  1. Using -tableView:willSelectRowAtIndexPath: to unset the shadow with cell.textLabel.shadowColor = nil but this doesn't work in time - the shadow gets unset only after the blue select style is applied.
  2. Checking cell.selected in tableView:cellForRowAtIndexPath: before setting the shadow but this obviously doesn't work since the cell is not redrawn after a selection.

I also tried overriding the -tableView:willDisplayCell:forRowAtIndexPath: delegate method as Kevin suggested below. From logging statements I put in, this delegate method is only called just before a cell is drawn - by the time a cell is touched, it is already too late. This is the code I used

(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
  NSLog(@"in willDisplayCell");
  if (cell.highlighted || cell.selected) {
    NSLog(@"drawing highlighed or selected cell");
    cell.textLabel.shadowColor = nil;
  } else {
    cell.textLabel.shadowColor = [UIColor whiteColor];
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way which should work is to extend UITableViewCell and override the setSelected AND setHighlighted methods, setting the drop shadow state accordingly. This will make sure it's painted at the same time as the background highlight update.

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
    [super setHighlighted:highlighted animated:animated];
    [self applyLabelDropShadow:!highlighted];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    [self applyLabelDropShadow:!selected];
}

- (void)applyLabelDropShadow:(BOOL)applyDropShadow
{
    self.textLabel.shadowColor = applyDropShadow ? [UIColor whiteColor] : nil;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...