开发者

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 开发者_StackOverflow中文版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!


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


Typically it's pretty simple to detect selection/highlighting and change colors depending on it. The important methods are:

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

note that when overriding you have to use the methods with animated:, otherwise it won't work.

When you want to change only the color, the simplest solution is to let the color to be set on the label and not on the string. Note that the attributed string is still inheriting all the properties of the UILabel.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜