我有一个 SwiftUI 应用程序,其工具栏包含多个 WindowGroup。我希望除主窗口之外的所有窗口都具有一个行为类似于预览应用程序的工具栏,在全屏时隐藏/折叠工具栏。
我已将 .presentedWindowToolbarStyle(.unified) 附加到我的 View ,并将 .windowStyle(.titleBar) 附加到我的 WindowGroups。
我尝试过寻找方法,多次询问 ChatGPT,也尝试过寻找带有折叠工具栏的开源 SwiftUI 应用程序,但它们都不起作用,因为它们要么是关于 iOS 的,要么是关于 AppKit 应用程序的。在代码中,我尝试了 .windowStyle 和 .presentedWindowToolbarStyle 的不同设置以及设置 .windowToolbarStyle。
最佳答案
我通过执行以下操作成功实现了这一目标:
- 首先获取对底层窗口的引用
- 将窗口的委托(delegate)设置为实现
willUseFullScreenPresentationOptions
的自定义委托(delegate)
第一步,您可以创建一个 NSViewRepresentable
,如下所示:
struct HostingWindowFinder: NSViewRepresentable {
var callback: (NSWindow?) -> ()
func makeNSView(context: Self.Context) -> NSView {
let view = NSView()
DispatchQueue.main.async { self.callback(view.window) }
return view
}
func updateNSView(_ nsView: NSView, context: Context) {
DispatchQueue.main.async { self.callback(nsView.window) }
}
}
现在创建自定义委托(delegate),如下所示:
class CustomWindowDelegate: NSObject, NSWindowDelegate {
override init() {
super.init()
}
func window(_ window: NSWindow, willUseFullScreenPresentationOptions proposedOptions: NSApplication.PresentationOptions = []) -> NSApplication.PresentationOptions {
return [.autoHideToolbar, .autoHideMenuBar, .fullScreen]
}
}
最后,在您看来,执行以下操作来设置窗口委托(delegate):
struct ContentView: View {
private var customWindowDelegate = CustomWindowDelegate()
var body: some View {
Text("Hello World")
.background {
HostingWindowFinder { window in
guard let window else { return }
window.delegate = self.customWindowDelegate
}
}
}
}
现在,每当您的 ContentView
全屏显示时,它都会自动隐藏工具栏,可以通过将光标移动到顶部来显示该工具栏。
关于swift - 全屏时如何隐藏 SwiftUI 中的工具栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76366878/