snibbe
snibbe

Reputation: 2738

How to set color of NSPopupButton Menu Item

How do you set the color of an NSPopupButton Menu Item?

Upvotes: 20

Views: 6247

Answers (3)

snibbe
snibbe

Reputation: 2738

Searching online, I only found a really hacked, contorted answer to this question, 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];
}

Upvotes: 3

SouthernYankee65
SouthernYankee65

Reputation: 1269

Swift 5.5

Assign an attributed string to the menu item. For example, I change the title color by assigning a bold green attributed string if the item was previously selected.

I have a property that I set for the previously selected title, so I can easily remove the attributed string if another title is selected.

var previousTitle: String = ""

Then in my method, I do the following

if !previousTitle.isEmpty {
    // Remove the previously assigned attributed title
    myPopUpButton.selectItem(withTitle: previousTitle)
    myPopUpButton.selectedItem?.attributedTitle = nil
}
previousTitle = <some previously selected title>
myPopUpButton.selectItem(withTitle: previousTitle)
let font = NSFont.systemFont(ofSize: 13).bold
let foreground = NSColor.green
let attrString = NSAttributedString(string: previousTitle, attributes: [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: foreground])
myPopUpButton.selectedItem?.attributedTitle = attrString

Upvotes: 0

nyamakawa
nyamakawa

Reputation: 1

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

Upvotes: 0

Related Questions