在 macOS 上的 SwiftUI NavigationView 中切换侧边栏 [英] Toggle Sidebar in SwiftUI NavigationView on macOS
问题描述
我有一个带有 NavigationView
的 macOS 应用程序,并且希望在窗口的工具栏中拥有默认的 ToggleSidebar 项.
I have a macOS Application with a NavigationView
and want to have the default ToggleSidebar item in the toolbar of the window.
目前我在 NSToolbarDelegate
的 toolbarWillAddItem(_)
中将 ToolbarItem 的目标设置为 AppDelegate.
Currently I set the target of the ToolbarItem to the AppDelegate in toolbarWillAddItem(_)
of the NSToolbarDelegate
.
我实现的 AppDelegate 内部
Inside of the AppDelegate I implemented
@objc func toggleSidebar(_ sender: Any) {
((window.contentView?.subviews.first?.subviews.first?.subviews.first as? NSSplitView)?.delegate as? NSSplitViewController)?.toggleSidebar(self)
}
此解决方案目前正在发挥作用.如果 SwiftUI 的实现会改变这一点.
This solution is working right now. If the implementation of SwiftUI will change this breaks.
那么如何才能以更好的方式做到这一点?
推荐答案
从 macOS Big Sur beta 4 开始,您可以使用 SwiftUI 2.0 添加默认侧边栏命令.
Since macOS Big Sur beta 4 you can add default sidebar commands with SwiftUI 2.0.
var body: some Scene {
WindowGroup {
NavigationView {
Group {
SidebarView()
ContentView()
}
}
}
.commands {
SidebarCommands()
}
}
此代码将添加切换侧边栏";快捷方式:
This code will add the "Toggle Sidebar" shortcut:
侧边栏视图代码:
var body: some View {
List {
ForEach(0..<5) { index in
Text("\(index)")
}
}
.listStyle(SidebarListStyle())
}
这篇关于在 macOS 上的 SwiftUI NavigationView 中切换侧边栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!