Home > Mobile >  Having different sections with List for each element
Having different sections with List for each element

Time:07-24

I want to have different sections for each element i have in List and each different section have different data sheet to display too. This is my tried code i made my sections like i wanted but the data sheet did not display.

list with sections

  struct ListsView: View {

 @State var states: [String] = ["CA", "MA"]
 @State var block1: [String] = ["John", "Emma", "Winny"]
 @State var block2: [String] = ["Supreme", "Jax", "Louis"]
var body: some View {
    List(states, id: \.self) { state in
        Section(header: Text(state)) {
            List(block1, id: \.self) { b1 in
                Text(b1)
            }
            List(block2, id: \.self) { b2 in
                Text(b2)
            }
        }
    }
  }
 }

CodePudding user response:

You do not need sub lists inside your first List. Instead you can achieve this design with a condition logic plus one section inside the first List.

Code is below the image: enter image description here

struct ListsView: View {
@State var states: [String] = ["CA", "MA"]
@State var block1: [String] = ["John", "Emma", "Winny"]
@State var block2: [String] = ["Supreme", "Jax", "Louis"]
 var body: some View {
    List(states, id: \.self) { state in
        Section(header: Text(state)) {
            ForEach(state == "CA" ? block1 : block2, id: \.self) { b in
                Text(b)
            }
        }
       
    }
  }
}
  • Related