简体   繁体   中英

UILabel shadow from custom cell selected color

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.

截图

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

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

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM