swift - 全屏时如何隐藏 SwiftUI 中的工具栏?

标签 swift macos swiftui toolbar

我有一个 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/

相关文章:

ios - SwiftUI 我自己的渲染函数的返回类型是什么?

swiftui - 弹出窗口后呈现工作表

swift - 如何模拟从 Mac App 到其他应用程序的鼠标点击

excel - 如何从 Excel Mac 访问 Postgres 数据库?

swift - 如何在 CGAffineTransform 上为 SwiftUI 中的 rotationAngle 添加动画?

objective-c - 如何将 Swift 代码导入到 Objective-C?

ios 检查用户是否登录到 icloud,如果没有则将用户发送到设置

swift - 警报消息无法出现

ios - Swift:当组合不是一个好的选择时,共享与状态相关的逻辑

Java SWT 更改所选小部件上的标签文本在 Mac 上不起作用