Keep window always on top?

2019-01-10 14:31发布

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'

2条回答
神经病院院长
2楼-- · 2019-01-10 15:10

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

    override func viewWillAppear() {            
        NSApplication.sharedApplication().activateIgnoringOtherApps(true)
    }
查看更多
Melony?
3楼-- · 2019-01-10 15:23

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
查看更多
登录 后发表回答