【问题标题】:display index of each item in forEach loop in swift ui [closed]在swift ui中的forEach循环中显示每个项目的索引[关闭]
【发布时间】:2022-01-14 02:12:28
【问题描述】:

我想在 SwiftUI 视图中显示 ForEach 循环中每个项目的索引。我尝试使用计数并每次都增加它,但 Xcode 给出错误“无法符合视图”

【问题讨论】:

  • 很难知道没有代码你到底在问什么,但也许你正在寻找enumerated()
  • 要么迭代数组的indices,要么迭代数组的enumerate
  • 请分享您的代码示例以了解您在做什么以及问题出在哪里

标签: swift swiftui


【解决方案1】:

对于 Swift 使用 .enumerated() 和数组来获取 for 循环中项目的索引

let array = ["element1", "element2", "element3", "element4"]

for (index,item) in array.enumerated() {
  print(index,item)
}

对于 SwiftUI,此链接将为您提供帮助

Get index in ForEach in SwiftUI

使用范围和计数

struct ContentView: View {
    @State private var array = [1, 1, 2]

    func doSomething(index: Int) {
        self.array = [1, 2, 3]
    }
    
    var body: some View {
        ForEach(0..<array.count) { i in
          Text("\(self.array[i])")
            .onTapGesture { self.doSomething(index: i) }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 2020-02-25
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    相关资源
    最近更新 更多