Search code examples
swiftmacosnswindow

Keep window always on top?


In Objective-C for Cocoa Apps it's possible to use such way to keep window always on top?

How to achieve the same with Swift?

self.view.window?.level = NSFloatingWindowLevel

Causes build error Use of unresolved identifier 'NSFloatingWindowLevel'


Solution

  • 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