您可以实现菜单的delegate
以在突出显示项目时得到通知。
#pragma mark - NSMenuDelegate
- (void)menu:(NSMenu *)menu willHighlightItem:(NSMenuItem *)item {
[menu.highlightedItem nik_restoreTextColor];
[item nik_overrideTextColor:[NSColor selectedMenuItemTextColor]];
}
它应该是非常简单的删除和重新添加单个项目的颜色。 但是,这里是我用来记住和以后恢复颜色的通用解决方案:
@implementation NSMutableAttributedString(NIKExchangeAttribute)
- (void)nik_renameAttribute:(NSString *)originalAttribute to:(NSString *)newAttribute {
NSRange fullRange = NSMakeRange(0, self.length);
[self removeAttribute:newAttribute range:fullRange];
[self enumerateAttribute:originalAttribute
inRange:fullRange
options:0
usingBlock:^(id value, NSRange range, BOOL *stop) {
[self addAttribute:newAttribute value:value range:range];
}];
[self removeAttribute:originalAttribute range:fullRange];
}
@end
static NSString *const ORIGINAL_COLOR_KEY = @"nik_originalColor";
@implementation NSMenuItem(NIKOverrideColor)
- (void)nik_overrideTextColor:(NSColor *)textColor {
NSMutableAttributedString *title = [self.attributedTitle mutableCopy];
[title nik_renameAttribute:NSForegroundColorAttributeName to:ORIGINAL_COLOR_KEY];
[title addAttribute:NSForegroundColorAttributeName
value:textColor
range:NSMakeRange(0, title.length)];
self.attributedTitle = title;
}
- (void)nik_restoreTextColor {
NSMutableAttributedString *title = [self.attributedTitle mutableCopy];
[title nik_renameAttribute:ORIGINAL_COLOR_KEY to:NSForegroundColorAttributeName];
self.attributedTitle = title;
}
@end