Search code examples
macosswiftuifullscreennswindowtitlebar

NSWindow contentView not cover full window size - macOS & SwiftUI


I'm starting a new macOS app with SwiftUI but I have a big problem. The app needs a full size contentView (underneath titleBar) but I can't accomplish. On a new project using Storyboards works fine, but with SwiftUI not.

My code: enter image description here

Result: enter image description here

And it should look like this: enter image description here

Any ideas? Thanks!


Solution

  • I just used the following variant in AppDelegate, the content of ContentView and others can be any

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Create the SwiftUI view that provides the window contents.
        let contentView = ContentView()
            .edgesIgnoringSafeArea(.top) // to extend entire content under titlebar 
    
        // Create the window and set the content view. 
        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .texturedBackground, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)
        window.center()
        window.setFrameAutosaveName("Main Window")
    
        window.titlebarAppearsTransparent = true // as stated
        window.titleVisibility = .hidden         // no title - all in content
    
        window.contentView = NSHostingView(rootView: contentView)
        window.makeKeyAndOrderFront(nil)
    }