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.
What am I doing wrong?
CodePudding user response:
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)