Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setHighlightedTextColor @ NSAttributedString

I have a custom UITableViewCell which uses a NSAttributedString. I want it to change color when the cell is selected. How can I make the NSAttributedString have the same behavior as a UILabel with highlightedTextColor set?

I have tried to change the color at the functions setSelected and setHighlighted of the cell, but it seems that they are called to late (on touchUpInside instead of touchDown)

Thanks in advance!

like image 640
Daniel Avatar asked Nov 14 '22 16:11

Daniel


1 Answers

UILabel subclass solution

@implementation CustomLabelHighlighted
{
    NSAttributedString *savedAttributedString;
}

-(void)setHighlighted:(BOOL)highlighted
{
    [super setHighlighted:highlighted];

    if (!highlighted) 
    {
       [super setAttributedText:savedAttributedString];
       return;
    }

    NSMutableAttributedString *highAttributedString = [savedAttributedString mutableCopy];
    NSRange range = NSMakeRange(0, highAttributedString.string.length);
    [highAttributedString addAttribute:NSForegroundColorAttributeName value:self.highlightedTextColor range:range];
    [super setAttributedText:highAttributedString];
}

- (void)setAttributedText:(NSAttributedString *)attributedText
{
    [super setAttributedText:attributedText];
    savedAttributedString = attributedText;
}

@end
like image 159
Uladzimir Avatar answered Jan 09 '23 03:01

Uladzimir