使用索引在ForEach循环SwiftUI中获取索引

时间:2020-09-11 11:49:51

标签: ios swift iphone mobile 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'

我也尝试过使用索引,但由于索引不在循环中,因此显然无法使用

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)

1 个答案:

答案 0 :(得分:1)

indices的变体中,您应将self用作id

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

可能同时具有两者

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