【问题标题】:SwiftUI get position in ForeachSwiftUI 在 Foreach 中获得位置
【发布时间】:2021-03-05 10:42:56
【问题描述】:

我对 SwiftUI 比较陌生,遇到了一个问题。

我已经为我的数组构建了这个结构:

struct Outfit:Identifiable {
   var id = UUID()
   var user: String
   var amount: Double
   var rating: Double
}

我可以打印出我需要的所有信息:

ForEach(loader.outfitcards) { index  in
   // I need to know if it is the first, second, etc. time it runs
}

但我需要知道数组内部已经运行了多少次。 我已经在数组 +1 处尝试了一个 @state 变量,但 Swiftui 不允许我这样做,因为那不是视图。谁能帮我?我也无法让 indices() 或 enumerated() 工作,也无法在结构中使用 ID,因为它不是 range 或 int 对象。

【问题讨论】:

    标签: foreach swiftui


    【解决方案1】:

    您应该使用.enumerated(),将id 用作\.element.id

    ForEach(Array(loader.outfitcards.enumerated()), id: \.element.id) { (index: Int, outfit: Outfit) in
        /* ... */
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 2020-01-15
      • 1970-01-01
      • 2016-03-18
      相关资源
      最近更新 更多