【问题标题】:Dynamically add cells to SwiftUI LazyGrid将单元格动态添加到 SwiftUI LazyGrid
【发布时间】:2021-02-02 18:37:24
【问题描述】:

如何在 SwiftUI 中将单元格(而不是列)动态添加到某些 LazyVGrid? 以下代码应通过单击按钮添加 1 个单元格。它编译但不起作用。 我错过了什么?

import SwiftUI

struct GridContent: Identifiable {
    var id = UUID()
}

struct ContentView: View {

    @State var counter = [ GridContent() ]
    var gridLayout = [ GridItem() ]
       
    var body: some View {
        LazyVGrid(columns: gridLayout) {
            ForEach(counter.indices) { item in
                Text("\(item)")
            }
            Button(action: {
                counter.append(GridContent())
            }) {
                Image(systemName: "plus.circle.fill")
            }
        }
    }
}

【问题讨论】:

    标签: swiftui lazyvgrid


    【解决方案1】:

    在这种情况下,您应该使用ForEach 的动态变体,例如

    var body: some View {
        LazyVGrid(columns: gridLayout) {
            ForEach(counter.indices, id: \.self) { item in      // << here !!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多