How do I correctly pass a “cell item” to a .sheet from a SwiftUI LazyVGrid?

前端 未结 1 829
时光说笑
时光说笑 2020-12-22 00:17

Here is my example, and I can\'t tell if this is a bug or not. All my cells load correctly, but when I try to bring up the DetailView() as a sheet, the item pas

相关标签:
1条回答
  • 2020-12-22 00:32

    In such use-case it is more appropriate to use variant of sheet constructed with item, because sheet must be moved out of dynamic content (otherwise you create as many sheets as items in ForEach).

    Here is possible solution. Tested with Xcode 12 / iOS 14.

    // helper extension because .sheet(item:...) requires item to be Identifiable
    extension String: Identifiable {
        public var id: String { self }
    }
    
    struct GridView: View {
    
        @State private var selected: String? = nil
    
        let data = (1...755).map { "\($0)" }
        let columns: [GridItem] = Array(repeating: .init(.flexible(), spacing: gridSpacing), count: columnCount)
        let colCount: CGFloat = CGFloat(columnCount)
        var body: some View {
            GeometryReader { geo in
                ScrollView (showsIndicators: false) {
                    LazyVGrid(columns: columns, spacing: gridSpacing) {
                        ForEach(data, id: \.self) { item in
    
                            Button(action: {
                                selected = item      // store selected item
                            }) {
                                GridCell(item: item, size: (geo.size.width - (colCount * gridSpacing)) / colCount)
                            }
                        }
                    }
                }.sheet(item: $selected) { item in     // activated on selected item
                    DetailView(item: item)
                }
                .padding(.horizontal, gridSpacing)
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题