如果需要在 ForEach 循环视图中获取当前元素的索引,这里演示三种我比较推荐的食用方法,直接贴代码,简单易懂。
使用 enumerated() 获取索引
.enumerated() 修饰符会使用元素和索引配对来遍历每个元素,以下是 .enumerated() 获取Foreach 索引的示例代码
Array(items.enumerated())会创建一个包含元素索引和元素值的元组数组\.offset是元组中索引的键路径,用作ForEach的id参数,确保循环中每个元素唯一index和item分别是每次迭代中元组的索引和值
struct ContentView: View {
let items = ["Apple", "Swfit", "Codeun"]
var body: some View {
VStack {
ForEach(Array(items.enumerated()), id: \.offset) { index, item in
Text("ForEach 索引 Index = \(index), Value = \(item)")
}
}
}
}
使用 Range 范围获取索引
可以使用 aRange 范围来迭代,aRange 范围本身就是一个符合Sequence协议的集合,可以直接将它作为 ForEach 的输入参数,然后在 ForEach 中获取索引,以下是示例代码:
struct ContentView: View {
let items = ["Apple", "Swfit", "Codeun"]
var body: some View {
VStack {
// 0..<items.count 就是 aRange 范围
ForEach(0..<items.count, id: \.self) { index in
Text("ForEach 索引 Index = \(index), Value = \(items[index])")
}
}
}
}使用 indices 集合来访问索引
可以使用数组的 indices 属性来在 ForEach 中访问索引。数组的 indices 属性返回一个包含数组所有索引的范围。这对于在 ForEach 循环中同时需要数组的索引和对应元素时非常有用。
struct ContentView: View {
let items = ["Apple", "Swfit", "Codeun"]
var body: some View {
VStack {
ForEach(items.indices, id: \.self) { index in
Text("ForEach 索引 Index = \(index), Value = \(items[index])")
}
}
}
} 本文自 https://www.codeun.com 发布,相应代码均自主编写并严格审阅和测试,完整代码中包含丰富的学习笔记和使用方式、实用技巧。
· 如若转载,请注明出处:https://www.codeun.com/archives/1283.html ·