How to give NSWindow a particular background color

2019-02-12 03:08发布

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?

4条回答
时光不老,我们不散
2楼-- · 2019-02-12 03:44

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

Like this:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Option 1
    [self.window setBackgroundColor: NSColor.whiteColor];
    // Option 2 - using dot syntax
    self.window.backgroundColor = NSColor.whiteColor;
}
查看更多
走好不送
3楼-- · 2019-02-12 03:44

The simplest way to change window background is to set it directly in your .xib file.

No code at all:

  1. Select your window (NSWindow class should appear in Class field)
  2. Click [+] button under the User Defined Runtime Attributes
  3. Type "backgroundColor" and select Color

Window Properties in XCode

查看更多
Deceive 欺骗
4楼-- · 2019-02-12 04:05

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

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

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

查看更多
在下西门庆
5楼-- · 2019-02-12 04:08

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.

查看更多
登录 后发表回答