我正在开发一个应用程序(macOS、SwiftUI),它为其他应用程序提供覆盖窗口。
到目前为止,我的覆盖窗口出现在所有其他应用程序的顶部,并跟随焦点屏幕,但是当另一个应用程序处于全屏模式时,我的窗口不再出现在顶部。
我该如何解决这个问题?
这是我目前拥有的代码:
import SwiftUI
struct ContentView: View {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text("Hello, world!")
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
NSApp.setActivationPolicy(.accessory)
if let window = NSApplication.shared.windows.first {
window.isOpaque = false
window.backgroundColor = NSColor.clear
// Remove the title bar
window.styleMask = [.borderless, .fullSizeContentView]
// Keep the content but make the window background transparent
window.contentView?.wantsLayer = true
window.contentView?.layer?.backgroundColor = NSColor.clear.cgColor
// Keep window above all other and ignore mouse events
window.level = NSWindow.Level.screenSaver
window.ignoresMouseEvents = true
// Keep the window on all spaces
window.collectionBehavior = [.canJoinAllSpaces, .fullScreenPrimary]
}
}
}
NSWindow.Level.screenSaver
不是可用的最高级别,它的 rawValue
为 101。您可以尝试使用以下方法设置更高的值:
window.level = NSWindow.Level(rawValue: 1000)