1

Say I have the following code(A):

struct ItemListView: View {
    @State private var items: [Item]
    
    var body: some View {
        List(items, id: \.self) { item in
            DisclosureGroup(item.name) {
                item.itemDescription
            }
        } // List
    } // body
}

compared with(B):

struct ItemListView: View {
    @State private var items: [Item]
    
    var body: some View {
        List {
            ForEach(items, id: \.self) { item in
                DisclosureGroup(item.name) {
                    item.itemDescription
                }
            } // ForEach
        } // List
    } // body
}

In code A, when I tap on the disclosure indicator the itemDescription appears to the right of the name where as in the B the itemDescription appears below where the item's name is. Why is this? When should I use List(items, ...) vs. List { ForEach(items, ...) }?

EDIT: If this helps anyone, after placing the DisclosureGroup in an HStack, the same thing happens as in Code A:

HStack {
    DisclosureGroup(item.name) {
        Text(item.itemDescription)
    }
    Spacer()
}
.onTapGesture {
    print("PRINT")
}

Code A: Code B:

New Dev
  • 48,427
  • 12
  • 87
  • 129
Hunter Meyer
  • 314
  • 1
  • 10
  • Does this answer your question? [What is the difference between List and ForEach in SwiftUI?](https://stackoverflow.com/questions/56535326/what-is-the-difference-between-list-and-foreach-in-swiftui) – koen Jan 18 '21 at 12:55
  • @koen it certainly helps, thank you. I just think it's weird that different providing a List a collection to loop through does not work the same as having a List then just having a ForEach. Feels like the Code A should just be a shorthand for Code B, but perhaps I am wrong – Hunter Meyer Jan 18 '21 at 22:02

0 Answers0