Question

I am trying to tackle a problem which sounds pretty simple: changing the background color of an NSPopupButton.

Interface Builder only allows changing the style to a pre-defined one and doesn't allow changing the background color. Also, setting up an IBOutlet didn't help since NSPopupButton doesn't have a setBackgroundColor method.

I also tried subclassing NSPopupButton to override the drawRect method. Here's what I have tried:

- (void)drawRect:(NSRect)dirtyRect
{
    [[NSColor redColor] setFill];
    NSRectFill(dirtyRect);
}

This draws a red rectangle over the NSPopupButton rather than setting it as a background color.

Any ideas on how to go about solving this?

Was it helpful?

Solution

You should create a subclass of NSPopUpButtonCell, then override

- (void)drawBezelWithFrame:(NSRect)frame inView:(NSView *)controlView

NSPopupButtonCell is a subclass of NSButtonCell which defines several methods for drawing individual cell components, eg bezel, title, image.

You can then expand the NSPopupButton and change its cell subclass to your new subclass and it should use your drawing methods.

Cocoa primarily uses NSCell to handle drawing, unlike iOS

OTHER TIPS

Swift version of @DanBrooker's answer. The example shows setting a background color

class PopUpButtonCell: NSPopUpButtonCell {

    override func drawBezel(withFrame frame: NSRect, in controlView: NSView) {
        guard let context = NSGraphicsContext.current?.cgContext else { return }
        NSColor.red.setFill() // NSColor.white.setFill()
        context.fill(frame)
    }
}

The button is draw by the system, so there isn't a real way to set the background color in a way that the system draws it like you want.The only thing that you can do is to draw it in the drawRect method, also drawing the title, and drawing a portion of the rectangle. 

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top