SwiftUI 在 Foreach 中获得位置

Posted

技术标签:

【中文标题】SwiftUI 在 Foreach 中获得位置【英文标题】:SwiftUI get position in 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 对象。

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

以上是关于SwiftUI 在 Foreach 中获得位置的主要内容,如果未能解决你的问题,请参考以下文章