NSPopUpButton White text

2.5k Views Asked by At

I have created a NSPopUpButton in my app in a custom view which has a black fill. I would now like to make the NSPopUpButton have a white text color but I do not seem to be able to do this. How should I go about doing this?

Thanks

2

There are 2 best solutions below

4
On

Use -[NSButton setAttributedTitle:], bearing in mind that NSPopUpButton is a subclass of NSButton. Make a mutable copy of the attributed title, set its foreground color to white, and then set that as the new attributed title.

NSMutableAttributedString* myTitle = [[button.attributedTitle mutableCopy] autorelease];
NSRange allRange = NSMakeRange( 0, [myTitle length] );
myTitle addAttribute: NSForegroundColorAttributeName
    value: [NSColor whiteColor]
    range: allRange];
button.attributedTitle = myTitle;
0
On

That's easy. You just need to override the -[NSPopUpButtonCell drawTitle:withFrame:inView], and then can change everything about title, like color, font, frame , etc. Here is a example below. Hope that can help you.

Objective-C:

@interface MyPopUpButtonCell : NSPopUpButtonCell

@property (nonatomic, readwrite, copy) NSColor *textColor;

@end

@implementation MyPopUpButtonCell

- (NSRect)drawTitle:(NSAttributedString*)title withFrame:(NSRect)frame inView:(NSView*)controlView {
        NSRect newFrame = NSMakeRect(NSMinX(frame), NSMinY(frame)+2, NSWidth(frame), NSHeight(frame));
        if (self.textColor) {
            NSMutableAttributedString *newTitle = [[NSMutableAttributedString alloc] initWithAttributedString:title];
            NSRange range = NSMakeRange(0, newTitle.length);
            [newTitle addAttribute:NSForegroundColorAttributeName value:self.textColor range:range];
            return [super drawTitle:newTitle withFrame:newFrame inView:controlView];
        }else {
            return [super drawTitle:title withFrame:newFrame inView:controlView];
        }
    }

@end

Swift:

class MyPopUpButtonCell: NSPopUpButtonCell {
   var textColor: NSColor? = nil

   override
   func drawTitle(_ title: NSAttributedString, withFrame frame: NSRect, in controlView: NSView) -> NSRect {
        if self.textColor != nil {
            let attrTitle = NSMutableAttributedString.init(attributedString: title)
            let range = NSMakeRange(0, attrTitle.length)
            attrTitle.addAttributes([NSAttributedString.Key.foregroundColor : self.textColor!], range: range)
            return super.drawTitle(attrTitle, withFrame: frame, in: controlView)
        }else {
            return super.drawTitle(title, withFrame: frame, in: controlView)
        }
    }
}