[英]How to get the previous element in a SwiftUI ForEach?
我在 SwiftUI 中有一个这样的 ForEach:
ForEach(entries) { (e: MyType) in
NavigationLinkItem(entry: e)
}
现在我还需要将上一个条目传递给我的视图 (NavigationLinkItem) 以执行以下操作:
ForEach(entries) { (e: MyType) in
NavigationLinkItem(entry: e, sucessor: ...)
}
如何意识到这一点?
我会这样做。 假设您需要将一个对象传递给您的继任者。 我建议您将后继者设为可选
ForEach((0...entries.count-1), id:\.self) {i in
NavigationLinkItem(entry: self.entries[i], sucessor: i == 0 ? self.entries[0] : self.entries[i-1])
}
编辑:正如评论中所建议的,使用索引比使用计数更好。
ForEach((0...entries.indices), id:\.self) {i in
NavigationLinkItem(entry: self.entries[i], sucessor: i == self.entries.startIndex ? self.entries.first : self.entries[i-1])
}
为了保持ForEach
动态,找到以下可能的方法(假设MyType
是Identifiable
,并且后继是可选的)
ForEach(Array(entries.enumerated()), id: \.1.id) { (index, e) in
NavigationLinkItem(entry: e, sucessor: (index == 0 ? nil : self.entries[index - 1]))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.