Raghunath Sahoo
Raghunath Sahoo

Reputation: 23

How to colour the titlebar of NSWindow

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.

Upvotes: 1

Views: 2694

Answers (1)

Charles Srstka
Charles Srstka

Reputation: 17060

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:

enter image description here

with these window settings:

enter image description here

resulting in this:

enter image description here

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.

Upvotes: 1

Related Questions