Grinch
Grinch

Reputation: 187

How to color the title bar of the OS X app with swift

Example

I am using Xcode 7.2.1 with Swift 2 to develop OS X app. I want the app to be filled with colour. How do I do it as on the example picture above?

I did this to get rid of the title bar:

  override func viewDidAppear() {
    super.viewDidAppear()

   self.view.wantsLayer = true


    self.view.window?.titlebarAppearsTransparent = true
    self.view.window?.movableByWindowBackground = true
    self.view.window?.titleVisibility = NSWindowTitleVisibility.Hidden

}

Upvotes: 3

Views: 6886

Answers (4)

anasaitali
anasaitali

Reputation: 1514

Simply add this in your AppDelegate after the window creation:

window.titlebarAppearsTransparent = true
window.backgroundColor = .red

Tested with OSX 10.15 and a project created as a SwiftUI app.

Upvotes: 0

mangerlahn
mangerlahn

Reputation: 4966

Alternative

If you want to only set a background color for the whole NSWindow and hide the title bar, you can set its styleMask to textured:

self.view.window?.styleMask = NSTexturedBackgroundWindowMask
self.view.window?.backgroundColor = NSColor.redColor()

The advantage of this: It is backwards compatible to at least OS X 10.6

Upvotes: 4

pbodsk
pbodsk

Reputation: 6876

If I move your "get rid of the title bar" code to the AppDelegate and sets the window.backgroundColor like so:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application

        window?.titlebarAppearsTransparent = true
        window.movableByWindowBackground = true
        window.titleVisibility = NSWindowTitleVisibility.Hidden
        window.backgroundColor = NSColor.redColor()

        let viewController = ViewController()
        window.contentViewController = viewController
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }
}

And then just set the color in the view controller as well:

override func viewDidLoad() {
    super.viewDidLoad()
    view.wantsLayer = true
    view.layer?.backgroundColor = NSColor.redColor().CGColor
}

I end up with this window enter image description here

The funny thing is that I have to set the color in both places, so maybe the solution @joshua-nozzi suggests is a safer bet

Upvotes: 2

Joshua Nozzi
Joshua Nozzi

Reputation: 61228

Add a custom subview with your background color. Or (better) set that custom view as your window's content view.

Upvotes: -2

Related Questions