【问题标题】:Using Indices to get Index in a ForEach loop SwiftUI使用索引在 ForEach 循环 SwiftUI 中获取索引
【发布时间】:2020-09-11 11:49:51
【问题描述】:

我是 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)

【问题讨论】:

    标签: ios swift iphone mobile swiftui


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-06
      • 2014-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-18
      • 1970-01-01
      • 2020-02-25
      相关资源
      最近更新 更多