保持窗口始终在顶部?

问题描述:

在 Cocoa 应用程序的 Objective-C 中,是否可以使用这种方式使窗口始终位于顶部?

In Objective-C for Cocoa Apps it's possible to use such way to keep window always on top?

如何用 Swift 实现同样的效果?

How to achieve the same with Swift?

self.view.window?.level = NSFloatingWindowLevel

导致构建错误Use of unresolved identifier 'NSFloatingWindowLevel'

要更改窗口级别,您不能在 viewDidload 中执行此操作,因为视图的 window 属性在那里始终为 nil,但可以通过覆盖 viewDidAppear 方法或任何其他方法来完成在窗口中安装视图后运行的方法(不要在 viewDidLoad 中使用它):

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 any other method that runs after view is installed in a window (do not use it inside viewDidLoad):

Swift 4 或更高版本

override func viewDidAppear() {
    super.viewDidAppear()
    view.window?.level = .floating
}

对于较旧的 Swift 语法,请检查编辑历史

For older Swift syntax check the edit history