簡體   English   中英

使用索引在 ForEach 循環中獲取索引 SwiftUI

[英]Using Indices to get Index in a ForEach loop SwiftUI

我是 SwiftUI 的新手,我正在嘗試獲取以下 ForEach 循環的索引

ForEach(self.postViewModel.posts, id: \.postId) { post in
                      
                                                       HStack(alignment: .top, spacing: 25) {
                                                           Header(post : post)
                                                           Footer(post: post)
                                                       

我嘗試使用如下索引:

 ForEach(self.postViewModel.posts.indices, id: \.postId) { post in

但我收到了這個錯誤

Value of type 'Range<Array<Post>.Index>.Element' (aka 'Int') has no member 'postId'

我也嘗試過使用 index 但顯然它不起作用,因為 index 不在循環中

ForEach(self.postViewModel.posts, id: \.postId) { post in
                           
                                                           HStack(alignment: .top, spacing: 25) {
                                                               Header(post : post)
                                                               Footer(post: post)
                                                           Text("#\(index)").frame(width: 45, height: 30)

indices的變體中,您應該使用self作為id

ForEach(self.postViewModel.posts.indices, id: \.self) { post in

可能的變體同時具有

ForEach(Array(self.postViewModel.posts.enumerated()), 
    id: \.1.postId) { (index, post) in

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM