如何为每个单元格从数字1开始为列表分配数字?
这是我的数据:
以及删除或添加单元格编号时动态重置
有我的代码:
struct ContentView: View {
var allUsers = ["name1", "name2", "name3", "name4"]
var body: some View {
List {
ForEach(allUsers, id: \.self) { user in
HStack {
Text("1")
Text(user)
}
}
}
}
}
答案 0 :(得分:0)
像下面一样使用ForEach
ForEach(0..<allUsers.count) { indexNumber in
HStack {
Text("\(indexNumber + 1)")
Text(self.allUsers[indexNumber])
}
}
答案 1 :(得分:0)
怎么样……
struct ContentView: View {
var allUsers = ["name1", "name2", "name3", "name4"]
var body: some View {
List {
ForEach(allUsers, id: \.self) { user in
HStack {
// Adding 1 here as the index function returns 0 for the first index
Text("\(allUsers.index(of: user)! + 1)")
Text(user)
}
}
}
}
}