我有一个使用 NSAttributedString 的自定义 UITableViewCell。我希望它在选择单元格时改变颜色。如何使 NSAttributedString 具有与设置了 highlightTextColor 的 UILabel 相同的行为?
我试图在单元格的 setSelected 和 setHighlighted 函数中更改颜色,但似乎它们被调用到较晚(在 touchUpInside 而不是 touchDown 上)
提前致谢!
我有一个使用 NSAttributedString 的自定义 UITableViewCell。我希望它在选择单元格时改变颜色。如何使 NSAttributedString 具有与设置了 highlightTextColor 的 UILabel 相同的行为?
我试图在单元格的 setSelected 和 setHighlighted 函数中更改颜色,但似乎它们被调用到较晚(在 touchUpInside 而不是 touchDown 上)
提前致谢!
UILabel 子类解决方案
@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
通常,检测选择/突出显示并根据它更改颜色非常简单。重要的方法是:
-(void)setHighlighted:animated:
-(void)setSelected:animated:
请注意,在覆盖时,您必须使用 with 的方法animated:
,否则它将不起作用。
当您只想更改颜色时,最简单的解决方案是让颜色设置在标签上而不是字符串上。请注意,属性字符串仍然继承UILabel
.