Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep window always on top?

People also ask

How do I keep a window always on top Windows 11?

Use the “Ctrl + Space” shortcut (or the shortcut you created) to pin a window on top.

How do you make a window always on top of Chrome?

Then when you use the Chrome browser, press Ctrl + Space to make Chrome always on top, and press Ctrl + Space again to incapacitate the Chrome browser, always on top.


To change the window level you can't do it inside viewDidload because view's window property will always be nil there but it can be done overriding viewDidAppear method or any other method that runs after view is installed in a window (do not use it inside viewDidLoad):

Swift 4 or later

override func viewDidAppear() {
    super.viewDidAppear()
    view.window?.level = .floating
}

For older Swift syntax check the edit history


I would prefer this way. This ignores all other active apps, and makes your app upfront.

    override func viewWillAppear() {            
        NSApplication.sharedApplication().activateIgnoringOtherApps(true)
    }

While the other answers are technically correct - when your app will or did resigns active, setting the window level to .floating will have no effect.

.floating means on top of all the windows from the app you are working on, it means not on top of all apps windows.

Yes there are other levels available you could set, like kCGDesktopWindowLevel which you can and should not set in swift to make your window float above all.

None of them will change the fact that your window will go behind the focused and active apps window. To circumvent i chose to observe if the app resigns active notification and act accordingly.

var observer : Any;

override func viewDidLoad() {
    super.viewDidLoad()

    observer = NotificationCenter.default.addObserver(
        forName: NSApplication.didResignActiveNotification, 
        object: nil, 
        queue: OperationQueue.main ) { (note) in

        self.view.window?.level = .floating;

        // you can also make your users hate you, to take care, don't use them.
        //NSApplication.shared.activate(ignoringOtherApps: true)
        //self.view.window?.orderFrontRegardless();
    }
}

another way could be subclassing NSWindow and override the property .level with an always returning .floating, but the code above is less work and keeps control in the place where you want to set the window floating.