macOS SwiftUI桌面应用:从菜单栏打开窗口并置顶的实现方法
macOS SwiftUI 窗口始终置顶的实现方案
针对你的需求,优先使用SwiftUI原生能力实现窗口置顶,可参考以下两种方案:
方案一:SwiftUI原生windowLevel修饰符(macOS 14+)
在定义Window时,直接添加.windowLevel(.floating)修饰符,该层级会让窗口始终悬浮在普通窗口之上,完全基于SwiftUI原生配置:
Window("foobar", id: "foobar") { VStack { Text("Some Text ...") } .frame(width: 350, height: 250) } .windowLevel(.floating) // 设置窗口为悬浮层级
如果需要更高优先级(比如超过系统通知),可以使用.statusBar层级,或自定义层级如.windowLevel(.floating + 1)。
方案二:兼容旧版本(macOS 13及以下)
若需支持更早系统,可在View的onAppear回调中获取对应NSWindow并手动设置层级:
Window("foobar", id: "foobar") { VStack { Text("Some Text ...") } .frame(width: 350, height: 250) .onAppear { // 通过窗口ID匹配并设置置顶 if let window = NSApplication.shared.windows.first(where: { $0.identifier?.rawValue == "foobar" }) { window.level = .floating window.orderFrontRegardless() // 强制窗口前置 } } }
优化窗口打开逻辑
点击菜单栏按钮时,建议先激活应用再打开窗口,避免被其他应用遮挡:
Button("One") { NSApp.activate(ignoringOtherApps: true) // 激活当前应用 openWindow(id: "foobar") // 无需先调用dismissWindow,openWindow会自动前置已存在的窗口 }
内容的提问来源于stack exchange,提问作者Johannes Bittner
相关产品推荐
相关产品推荐

