2013-12-21 66 views
2

This answer描述如何设置NSMenuItem的字体以及字体颜色。设置NSMenuItem的字体颜色以突出显示

为了提醒用户在弹出菜单中选择的项目有问题,我将颜色设置为红色。很好用,除非项目突出显示,背景变成蓝色,而我的红蓝色很难看清,看起来很糟糕。常规菜单项的字体从黑色变为白色。我希望修改后的菜单项在突出显示时改变它的字体颜色。

这是一个动态菜单。当创建项目时,我在-menuNeedsUpdate中设置字体/颜色。当然, - [NSMenuItem isHighlighted]在那里返回NO,因为该项目刚创建。

我也尝试添加上NSMenuDidBeginTrackingNotification和NSMenuDidBeginTrackingNotification观察员,但要么是因为这两个通知总是成对接受,三到六个月对我每次点击菜单没有帮助,再经过跟踪已经结束另一个-menuNeedsUpdate:它再次从头开始重新创建所有内容。我不确定当菜单“跟踪”时它意味着什么,但显然它不是我想要的。

我认为我会问是否有人曾经想出了一个很好的答案对于这一点,我才熄灭,做一些真的 kludgey喜欢these guys did for a similar NSMenuItem quandary

回答

3

您可以实现菜单的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 
相关问题