Steve Jiang Steve Jiang - 4 months ago 22
Swift Question

how to keep window always on the top with swift?

I just create a new application project
 1. Xcode Version 7.3 (7D175)

 2.swift Version 2.2

 3.Mac OS version OS X EI Capitan 10.11.4

I want to make a desktop app for Mac OS and
I had set the window level but it's not work.

Answer

You need check window != nil before any custom code

class ViewController: NSViewController {
    var addedObserver = false

    override func viewDidLoad() {
        super.viewDidLoad()

        if let window = self.view.window {
            // custom window here
            window.level = Int(CGWindowLevelForKey(.FloatingWindowLevelKey))
        } else {
            addedObserver = true
            self.addObserver(self, forKeyPath: "view.window", options: [.New, .Initial], context: nil)
        }
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if let window = self.view.window {
            // custom window here
            window.level = Int(CGWindowLevelForKey(.FloatingWindowLevelKey))
        }
    }

    deinit {
        if addedObserver {
            self.removeObserver(self, forKeyPath: "view.window")
        }
    }
}