开发者

Changing color of the NSWindow titlebar

开发者 https://www.devze.com 2023-01-04 00:28 出处:网络
I am dev开发者_开发技巧eloping a desktop application in which I want to change the color of the title bar of an NSWindow. How exactly can I do this?NSWindow\'s content view has a superview, which is a

I am dev开发者_开发技巧eloping a desktop application in which I want to change the color of the title bar of an NSWindow. How exactly can I do this?


NSWindow's content view has a superview, which is an instance of NSThemeFrame. That class is responsible for drawing the title text, the window/toolbar background texture, and it contains subviews for everything else (close button, full screen button, NSDocument icon, etc).

You can use the Objective-C runtime to replace NSThemeFrame's drawRect: method with your own method, which will call the parent implementation and then perform custom drawing on top of it.

There is also a private method to find the rect the title is drawn in, and public methods on NSFont to find it's font and font size.

What I did is set the window background colour to be a solid colour (black) instead of a gradient/texture, then set it to be a "textured" window (which causes the background colour to actually be rendered, otherwise it would not happen), then I draw a black square over the title bar in the area where I know the title has already been drawn, then draw my own title in it's place, with light grey instead of dark grey.

Source code is here: https://github.com/abhibeckert/Dux/blob/master/Dux/DuxProjectWindow.m (note: it only does a custom title text colour if DUX_DARK_MODE == 1)

Doing this will probably get your app blocked from the Mac App Store, but it is fairly reliable. Just make sure you test it with every new major version of OS X.


To change the color of the window's toolbar:

  1. Set window style Textured in Attribute inspector.
  2. In code: [window setBackgroundColor: MyCustomColor];


This uses private methods, but works:

NSEnumerator *viewEnum = [[[[[[window contentView] superview] titlebarViewController] view] subviews] objectEnumerator];
NSView *viewObject;

while(viewObject = (NSView *)[viewEnum nextObject]) {
   if([viewObject className] == @"NSTextField") [viewObject setTextColor: .. your color .. ];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消