Search code examples
iphoneobjective-cnsattributedstring

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!


Solution

  • 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