【发布时间】:2019-09-16 02:16:28
【问题描述】:
【问题讨论】:
-
您是否在设置级别之前检查了窗口存在(!= nil)?
标签: swift
【问题讨论】:
标签: swift
让您的应用始终在 Swift 5 中的其他应用之上非常简单。
override func viewDidAppear() {
view.window?.level = .floating
}
【讨论】:
您需要在任何自定义代码之前检查窗口!= nil
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")
}
}
}
【讨论】:
仍在测试它,但这是 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)
}
}
【讨论】: