您可以實現菜單的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