SwiftUI 和 Mac Catalyst:侧边栏显示不正确

问题描述

我为 Mac Catalyst 启用了 iPad App,但遇到了 display Problem 的奇怪 Sidebar

Screenshot of the Mac Catalyst App

代码

@State private var selection: NavigationItem? = .start

NavigationView {
    List(selection: $selection) {
        NavigationLink(destination: StartView(),tag: NavigationItem.start,selection: $selection) {
                Label("Start",systemImage: "square.grid.2x2.fill")
                    .accessibility(label: Text("Start"))
            }
            .tag(NavigationItem.start)

        // 4 more Items
    }
    .listStyle(SidebarListStyle())
    .navigationBarTitle("Impfpass+")
        
    StartView()
}

问题:代码Standard Sidebar生成 iPad,但是,如您所见,Mac Version 与此 {{1 }}。我怎样才能达到angular design

解决方法

我遇到了同样的问题。

结果是内置的 SidebarListStyle 在 macOS 上运行不正确。

Here 是 Steven Troughton-Smith 建议的解决方案,它意味着将 SwiftUI 视图包装在 UISplitViewController 中。

基本上:

struct SidebarSplitView: View,UIViewControllerRepresentable {
    typealias UIViewControllerType = UISplitViewController
    let splitViewController = UISplitViewController(style: .doubleColumn)
    
    var columnA = UIViewController()
    var columnB = UIViewController()
    
    init<A:View,B:View>(@ViewBuilder content: @escaping () -> TupleView <(A,B)>) {
        let content = content()
        columnA = UIHostingController(rootView: content.value.0)
        columnB = UIHostingController(rootView: content.value.1)
        columnA.view.backgroundColor = .clear
        columnB.view.backgroundColor = .clear
        splitViewController.viewControllers = [columnA,columnB]
    }
    
    func makeUIViewController(context: Context) -> UIViewControllerType {
        splitViewController.primaryBackgroundStyle = .sidebar
        return splitViewController
    }
    
    func updateUIViewController(_ uiView: UIViewControllerType,context: Context) { }
}

然后你就可以把它称为:

struct ContentView: View {
    var body: some View {
        SidebarSplitView {
            Sidebar()   // here goes your sidebar
            MainView()  // here your main view
        }
    }
}