如何使用Swift保持窗口始终处于顶部?

时间:2016-08-02 03:41:45

标签: swift

I just create a new application project

  • Xcode版本7.3(7D175)
  • Swift Version 2.2
  • Mac OS版本OS X El Capitan 10.11.4

我想为Mac OS制作桌面应用程序 我设置了窗口级别,但它不起作用。

3 个答案:

答案 0 :(得分:2)

在任何自定义代码

之前,您需要检查窗口!= 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")
        }
    }
}

答案 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
}