Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple List Sections in NavitagionSplitView Sidebar Only Shows a Single Item

I’m having a problem displaying all the list elements inside a list when there are multiple sections in the sidebar.

Here is an example code.

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationSplitView {
            List {
                Section("Test 1") {
                    List(0...20, id: \.self) { i in
                        Text("\(i)")
                    }
                }
                
                Section("Test 2") {
                    List(21...50, id: \.self) { i in
                        Text("\(i)")
                    }
                }
            }
            .listStyle(.sidebar)
        } detail: {
            Text("Details")
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

When I run this code, I get two sections; however the list under them are only showing a single item instead of all.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What am I doing wrong?

Sidebar List with Multiple Sections Issue

>Solution :

You are facing this issue because you are trying to create a nested List inside the section of List. Inside the section of the list, you need to use ForEach to loop through your data instead of creating a nested List.

List {
    Section("Test 1") {
        ForEach(0...20, id: \.self) { i in
            Text("\(i)")
        }
    }
    
    Section("Test 2") {
        ForEach(21...50, id: \.self) { i in
            Text("\(i)")
        }
    }
}
.listStyle(.sidebar)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading