Как установить цвет элемента меню NSPopupButton

Это ответ, а не вопрос. Поиск в Интернете я нашел на самом деле действительно взломанный, искаженный ответ на этот вопрос (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];
}

Ответы

Ответ 1

Просто обратите внимание, что вопрос на самом деле является ответом. В Интернете есть много ссылок со слишком сложными решениями, основанными на более старых API, и я подумал, что было бы полезно написать эту публикацию в качестве ссылки.

Ответ 2

У меня была такая же проблема.

Чтобы сохранить исходные текстовые атрибуты, мое решение находится здесь:

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];
}