views:

3303

answers:

4

I am writing a cocoa application which has a NSWindow. I want to change the background color of the window to a specific color. But the window properties in the inspector only provide "Textured Window" alternative. How can I make the color of the window as desired?

+1  A: 

You have to subclass NSWindow in order to change the background and then override the implementation for

- (id)initWithContentRect:(NSRect)contentRect
            styleMask:(unsigned int)styleMask
              backing:(NSBackingStoreType)bufferingType
                defer:(BOOL)flag

As an example see Mat Gemmell's HUDWindow: http://mattgemmell.com/2006/03/12/hudwindow

diciu
+4  A: 

As long as you only want to change the background color of the content area, not the frame and toolbar, you don't need to subclass NSWindow. What you do need to do is subclass NSView and make your custom view draw your desired color, then set an instance of that class as the window's content view.

Alternatively, you may be able to get away with setting a borderless NSImageView or NSColorWell as the content view, but I'm not sure that Apple means for those to have subviews. If not, you'd have to leave your window empty.

That said, you should be really sure that a custom background color is appropriate. Almost always, it's not, and you should stick with the Aqua or HUD appearance.

Peter Hosey
+4  A: 

Try calling the instance method setBackgroundColor: with a color on your window instance. What's in a name.. ;)

Dirk Stoop
+3  A: 

NSWindow has methods called setBackgroundColor and backgroundColor (as Dirk above alluded to), meaning you can even treat it as a pseudo-property and use dot syntax if you're into that, but it's not the whole story. If you're using a standard window as created in IB, the background color doesn't affect the title bar or toolbar. In order to cover the entire window, you'll need to set it as textured, like you mentioned attempting already. That should work for 99% of cases you'll need to handle.

If you need something completely custom, with your own custom-designed title bar or something, you'll need to start like diciu said, and create a window in code with the NSBorderlessWindowMask style mask. This will give you basically a rectangular "space" to draw whatever view you want, with completely custom everything (even shape, if you make the window itself transparent).

Arclite