小编Moh*_*med的帖子

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

我是 SwiftUI 新手,我正在尝试获取以下 ForEach 循环的索引

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

我尝试过使用索引,如下所示:

 ForEach(self.postViewModel.posts.indices, id: \.postId) { post in
Run Code Online (Sandbox Code Playgroud)

但我得到了这个错误

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

我也尝试过使用索引,但显然它不起作用,因为索引不在循环中

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)
Run Code Online (Sandbox Code Playgroud)

iphone mobile ios swift swiftui

2
推荐指数
1
解决办法
8808
查看次数

标签 统计

ios ×1

iphone ×1

mobile ×1

swift ×1

swiftui ×1