I want to make a desktop app for Mac OS and I had set the window level but it's not work.
Making your app always on top of the other applications in Swift 5
is so simple.
override func viewDidAppear() {
view.window?.level = .floating
}
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")
}
}
}
Still testing it, but this is Larva's answer in Swift 4 and it seems to be working.
var observingFloat = false
override func viewDidLoad() {
super.viewDidLoad()
self.view.wantsLayer = true
if self.view.window != nil {
NSApplication.shared.windows.first?.level = NSWindow.Level(rawValue: 1)
} else {
observingFloat = true
self.addObserver(self, forKeyPath: "view.window", options: [.new, .initial], context: nil)
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if self.view.window != nil {
NSApplication.shared.windows.first?.level = NSWindow.Level(rawValue: 1)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With