How to setHighlightedTextColor @NSAttributedString

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

I tried changing the color in the setSelected and setHighlighted functions from the cell, but it seems like they are called until late (on touchUpInside instead of touchDown)

Thanks in advance!

+5
source share
2 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
+1
source

It is usually quite easy to detect selection / selection and change colors depending on this. Important methods are:

-(void)setHighlighted:animated:
-(void)setSelected:animated:

, animated:, .

, , . , - UILabel.

0

All Articles