macOS SwiftUI如何让悬浮窗口在其他应用全屏时保持置顶?
解决macOS SwiftUI悬浮窗口在全屏模式下不置顶的问题
要让悬浮窗口在其他应用全屏时依然保持置顶,需要调整窗口的层级设置和集合行为,以下是具体修改方案:
关键修改点
- 提升窗口层级:将原有的
screenSaver层级替换为statusBar(或更高的popUpMenu),这个层级优先级更高,能覆盖全屏应用窗口 - 调整集合行为:把
fullScreenPrimary改为fullScreenAuxiliary,该属性允许窗口作为辅助元素显示在全屏应用之上 - 确保窗口初始化正确:主动创建自定义窗口,而非依赖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) // 主动创建自定义窗口,替代默认窗口 let contentView = ContentView() window = NSWindow( contentRect: NSRect(x: 100, y: 100, width: 200, height: 100), styleMask: [.borderless, .fullSizeContentView], backing: .buffered, defer: false ) window.contentView = NSHostingView(rootView: contentView) window.isOpaque = false window.backgroundColor = NSColor.clear window.contentView?.wantsLayer = true window.contentView?.layer?.backgroundColor = NSColor.clear.cgColor // 提升窗口层级至状态栏级别,确保全屏时置顶 window.level = NSWindow.Level.statusBar window.ignoresMouseEvents = true // 设置集合行为:支持所有空间+全屏辅助窗口 window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary] // 从窗口菜单中隐藏,避免干扰 window.excludedFromWindowsMenu = true // 允许通过窗口背景拖动(可选) window.isMovableByWindowBackground = true window.makeKeyAndOrderFront(nil) } }
额外说明
- 如果
statusBar层级仍不满足需求,可以尝试更高的NSWindow.Level.popUpMenu .fullScreenAuxiliary是macOS 10.11+引入的属性,确保你的部署目标版本符合要求- 主动创建窗口能更好地控制窗口属性,避免SwiftUI默认窗口的潜在冲突
内容的提问来源于stack exchange,提问作者Matthieu-OD
相关产品推荐
相关产品推荐

