如何设置NSPopupButton菜单项的颜色

时间:2011-01-19 05:19:04

标签: cocoa

这是一个答案,而不是一个问题。在线搜索,我发现这个问题(http://www.cocoabuilder.com/archive/cocoa/58379-changing-the-text-color-of-an-nsmenuitem-in-an-nspopupbutton.html)的答案真的被黑了,扭曲了,可以更优雅地回答:

NSArray *itemArray = [scalePopup itemArray];
int i;
NSDictionary *attributes = [NSDictionary
                            dictionaryWithObjectsAndKeys:
                            [NSColor redColor], NSForegroundColorAttributeName,
                            [NSFont systemFontOfSize: [NSFont systemFontSize]],
                            NSFontAttributeName, nil];

for (i = 0; i < [itemArray count]; i++) {
    NSMenuItem *item = [itemArray objectAtIndex:i];

    NSAttributedString *as = [[NSAttributedString alloc] 
             initWithString:[item title]
             attributes:attributes];

    [item setAttributedTitle:as];
}

2 个答案:

答案 0 :(得分:3)

请注意,上面的问题实际上就是答案。网上有很多链接,基于较旧的API的解决方案过于复杂,我认为将此帖子作为参考可能会有所帮助。

答案 1 :(得分:0)

我遇到了同样的问题。

要保留原始文字属性, 我的解决方案在这里:

NSRange range = NSMakeRange(0, 0);
NSAttributedString *cellStr = [[self.popup cell] attributedTitle];
NSMutableDictionary *cellAttr = [[cellStr attributesAtIndex:range.location effectiveRange:&range] mutableCopy];
[cellAttr setObject:[NSColor redColor] forKey:NSForegroundColorAttributeName];

NSArray *menuItems = [self.popup itemArray];    
for (NSMenuItem *menu in menuItems ) {
    NSString *orgTitle = [menu title];
    NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:orgTitle attributes:cellAttr];

    [menuItem setAttributedTitle:title];
}
相关问题