How to change the background color of an NSPopupButton?

十年热恋 提交于 2021-02-08 15:54:46

问题


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?


回答1:


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




回答2:


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. 



来源:https://stackoverflow.com/questions/13222205/how-to-change-the-background-color-of-an-nspopupbutton

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