I have a requirement to change the title bar of the NSWindow to red in colour. When I am changing the background color, the entire window is becoming red.
I just want to change the title background color.
Thanks.
In the window's Attributes Inspector in Interface Builder, turn on the "Transparent Title Bar" and "Full Size Content View" options. Then, put a red view at the top of the window's content view, and it should show up behind the title bar.
For the view, I just did this:
class RedView: NSView {
// draw is simple; just fill the rect with red
override func draw(_ dirtyRect: NSRect) {
NSColor.red.set() // maybe experiment to find a better-looking shade of red
dirtyRect.fill()
}
// provide an intrinsic content size, to make our view prefer to be the same height
// as the title bar.
override var intrinsicContentSize: NSSize {
guard let window = self.window, let contentView = window.contentView else {
return super.intrinsicContentSize
}
// contentView.frame is the entire frame, contentLayoutRect is the part not
// overlapping the title bar. The difference will therefore be the height
// of the title bar.
let height = NSHeight(contentView.frame) - NSHeight(window.contentLayoutRect)
// I just return noIntrinsicMetric for the width since the edge constraints we set
// up in IB will override whatever we put here anyway
return NSSize(width: NSView.noIntrinsicMetric, height: height)
}
}
and arranged it like this:
with these window settings:
resulting in this:
Be careful; with great power comes great responsibility. Take care not to make the interface hard to use for people with red-green colorblindness. Looking at the image above, I'd probably go with a lighter shade of red than NSColor.red, since the darkness of it obscures the title a bit. But you can experiment with that until you get something that looks good.
titlebarAppearsTransparent and styleMask properties.
Dec 11, 2017 at 21:00
RedView's height using contentLayoutRect instead of hard-coding it to 23. We can do that by 1) implementing intrinsicContentSize in the view, 2) setting vertical content hugging and compression resistance both to 1000 so it will be forced to use the intrinsic height, and 3) setting a placeholder size in IB so that the ambiguity warning will shut up. This should make the view sized the same as the title bar even if Apple changes the title bar's size in some future version of macOS. I've updated the answer.
Dec 11, 2017 at 21:09
NSAppearanceAPI and possibly this open source: github.com/luckymarmot/ThemeKit