【问题标题】:Set font color of NSMenuItem to alternate when highlighted将 NSMenuItem 的字体颜色设置为在突出显示时交替显示
【发布时间】:2013-12-21 18:53:42
【问题描述】:

This answer 描述了如何设置 NSMenuItem 的字体以及字体颜色。

为了提醒用户弹出菜单中所选项目的问题,我将颜色设置为红色。效果很好,除了突出显示该项目时,背景变成蓝色,而且我的红色蓝色很难阅读并且看起来很糟糕。常规菜单项的字体从黑色变为白色。我希望修改后的菜单项在像这样突出显示时更改其字体颜色。

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

我还尝试在 NSMenuDidBeginTrackingNotification 和 NSMenuDidBeginTrackingNotification 上添加观察者,但这也无济于事,因为这两个通知总是成对收到,每次单击菜单时会收到三到六对,然后在跟踪后有 结束 是另一个 -menuNeedsUpdate: 从头开始​​重新创建所有内容。我不确定菜单“跟踪”是什么意思,但显然这不是我想要的。

我想我会问是否有人为此想出了一个好的答案,然后我开始做一些真正these guys did for a similar NSMenuItem quandary这样的笨拙的事情。

【问题讨论】:

    标签: macos cocoa fonts nsmenuitem


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2014-12-24
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      相关资源
      最近更新 更多