How to set color of NSPopupButton Menu Item

≯℡__Kan透↙ 提交于 2021-02-05 22:50:16

问题


This is an answer, rather than a question. Searching online, I only found a really hacked, contorted answer to this question (http://www.cocoabuilder.com/archive/cocoa/58379-changing-the-text-color-of-an-nsmenuitem-in-an-nspopupbutton.html), which can be answered more elegantly like so:

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:


Just a note here that the question above is in fact the answer. There are a lot of links on the web with too complex solutions based on older APIs and I thought it would be helpful to write this posting as a reference.




回答2:


I just got a same problem.

To preserve original text attributes, my solution is here:

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


来源:https://stackoverflow.com/questions/4731982/how-to-set-color-of-nspopupbutton-menu-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!