Changing color of the NSWindow titlebar

元气小坏坏 提交于 2019-12-01 05:10:58

问题


I am developing a desktop application in which I want to change the color of the title bar of an NSWindow. How exactly can I do this?


回答1:


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.




回答2:


To change the color of the window's toolbar:

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



回答3:


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 .. ];
}


来源:https://stackoverflow.com/questions/3044303/changing-color-of-the-nswindow-titlebar

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