SwiftUI & Mac Catalyst: Sidebar is not displayed correctly

Viewed 397

I enabled Mac Catalyst for an iPad App and encountered an strange Display Problem of the Sidebar. Screenshot of the Mac Catalyst App Code:

@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()
}

Question: This Code produces a Standard Sidebar on the iPad, however, as you can see, the Mac Version is looking strange with this angular design. How can I achieve the Standard macOS Sidebar Design?

1 Answers

I was having the same issue.

Turns out the built-in SidebarListStyle does not behave correctly on macOS.

Here is a suggested solution by Steven Troughton-Smith that implies wrapping your SwiftUI views in a UISplitViewController.

Basically :

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) { }
}

Then you would be able to call it as :

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