swiftPunk
swiftPunk

Reputation: 1

How can I make my borderless Window be the Key Window after launch?

I am making a window without border or title, but after launch the window is not the key window with this code:

import Cocoa
import SwiftUI

class AppDelegate: NSObject, NSApplicationDelegate {
    
    private lazy var window: NSWindow = NSWindow()
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        
        window.styleMask = [.fullSizeContentView]
        window.backingType = .buffered            
        
        window.contentView = NSHostingView(rootView: ContentView())
        
        window.center()
        window.setFrameAutosaveName("Main Window")
        window.isMovableByWindowBackground = true
        
        window.makeKeyAndOrderFront(window)
        
    }
    
}

let nsApplication: NSApplication = NSApplication.shared
let appDelegate: AppDelegate = AppDelegate()
nsApplication.delegate = appDelegate
nsApplication.run()

The issue photo:

enter image description here

But it should be like:

enter image description here

I tried to solve the issue with window.makeKey() but it did not help also.

Upvotes: 0

Views: 506

Answers (1)

Darren
Darren

Reputation: 25619

A regular NSWindow is either borderless or titled. As per the documentation, borderless windows cannot become key or main unless you override the canBecomeMain and canBecomeKey properties.

You have two options. If you want a true borderless window then subclass NSWindow and override the override the canBecomeMain and canBecomeKey properties:

class AlwaysKeyWindow : NSWindow {
    override var canBecomeMain: Bool { return true }
    override var canBecomeKey: Bool { return true }
}

@main
class AppDelegate: NSObject, NSApplicationDelegate {
    private lazy var window = AlwaysKeyWindow()

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        window.styleMask = [ .borderless ] // Same as styleMask = []
        // ... etc ...
    }
}

Alternatively, you can use a normal window with a hidden/transparent title bar:

window.styleMask = [ .titled, fullSizeContentView ]
window.titleVisibility = .hidden
window.titlebarAppearsTransparent = true

This will behave like a regular window (it will appear in the "Window" menu and use the standard window shadows and corner radius) but it will not draw its title bar.

Upvotes: 3

Related Questions