我想为Mac OS制作桌面应用程序 我设置了窗口级别,但它不起作用。
答案 0 :(得分:2)
在任何自定义代码
之前,您需要检查窗口!= nilclass 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")
}
}
}
答案 1 :(得分:1)
仍在测试它,但这是Larva在Swift 4中的答案,它似乎正在发挥作用。
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)
}
}
答案 2 :(得分:1)
让您的应用始终位于Swift 5
中的其他应用之上非常简单。
override func viewDidAppear() {
view.window?.level = .floating
}