Swift 如何为每个单元格分配一个数字?
如何从数字1开始为每个单元格的列表分配数字 以下是我的数据: 并在删除或添加单元号时动态重置 这是我的代码:Swift 如何为每个单元格分配一个数字?,swift,swiftui,Swift,Swiftui,如何从数字1开始为每个单元格的列表分配数字 以下是我的数据: 并在删除或添加单元号时动态重置 这是我的代码: struct ContentView: View { var allUsers = ["name1", "name2", "name3", "name4"] var body: some View { List { ForEach(allUsers, id: \.self) { user in HS
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)
}
}
}
}
}
使用
ForEach
如下所示
ForEach(0..<allUsers.count) { indexNumber in
HStack {
Text("\(indexNumber + 1)")
Text(self.allUsers[indexNumber])
}
}
ForEach(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)
}
}
}
}
}