swiftmacoscocoanswindowcontroller

MacOs Swift App: How to make a window background with a gradient including title bar


I am trying to create a background of my Window Controller with a gradient. I was able to apply the background to the window but I can't seem to extend the gradient to the title bar. Can anyone give me some advice? Thanks!

This is my code. I would like to have a result like the one I captured in the second screenshot.

// Window Controller
import Cocoa

class HomeWindowController: NSWindowController {

    override func windowDidLoad() {
        super.windowDidLoad()

        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.window!.contentView!.bounds
        gradientLayer.colors = [color01, color02]
        self.window!.contentView!.layer = gradientLayer
    }
}

// In the AppDelegate

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Get the main window
        if let mainWindow = NSApplication.shared.windows.first {
            // Set the titlebar to transparent
            mainWindow.titlebarAppearsTransparent = true
            
            // Customize the titlebar appearance
            mainWindow.backgroundColor = NSColor.clear
        }
    }

current status desired status


Solution

  • To include title bar in gradient, add .fullSizeContentView to window style mask. Following code may be run in swift Xcode project by adding a new file called main.swift, copy/pasting this demo into it, and deleting pre-existing AppDelegate file.

    main.swift

    import Cocoa
    
    let app = NSApplication.shared
    app.setActivationPolicy(.regular)
    app.activate(ignoringOtherApps:true)
    
    var window:NSWindow!
    
    let _wndW : CGFloat = 400
    let _wndH : CGFloat = 300
    
     window = NSWindow(contentRect:NSMakeRect(0,0,_wndW,_wndH),styleMask:[.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing:.buffered, defer:false)
     window.center()
     window.title = ""
     let gradientLayer = CAGradientLayer()
     gradientLayer.frame = window!.contentView!.bounds
     gradientLayer.colors = [NSColor.green.cgColor, NSColor.yellow.cgColor]
     window!.contentView!.layer = gradientLayer
     window.titlebarAppearsTransparent = true
     window.makeKeyAndOrderFront(window)
    
    app.run()