问题
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'
回答1:
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 in a IBAction method:
Swift 1
override func viewDidAppear() {
super.viewDidAppear()
view.window?.level = Int(CGWindowLevelForKey(kCGFloatingWindowLevelKey))
}
Swift 2
view.window?.level = Int(CGWindowLevelForKey(.FloatingWindowLevelKey))
Swift 3
view.window?.level = Int(CGWindowLevelForKey(.floatingWindow))
Swift 4
Finally they fixed the odd syntax:
view.window?.level = .floating
回答2:
I would prefer this way. This ignores all other active apps, and makes your app upfront.
override func viewWillAppear() {
NSApplication.sharedApplication().activateIgnoringOtherApps(true)
}
来源:https://stackoverflow.com/questions/27396957/keep-window-always-on-top