Environment
Problem
In order to implement editable teble with TextField on SwiftUI, I used ForEach(0..<items.count)
to handle index.
import SwiftUI
struct DummyView: View {
@State var animals: [String] = ["??", "??"]
var body: some View {
List {
EditButton()
ForEach(0..<animals.count) { i in
TextField("", text: self.$animals[i])
}
}
}
}
However, problems arise if the table is changed to be deleteable.
import SwiftUI
struct DummyView: View {
@State var animals: [String] = ["??", "??"]
var body: some View {
List {
EditButton()
ForEach(0..<animals.count) { i in
TextField("", text: self.$animals[i]) // Thread 1: Fatal error: Index out of range
}
.onDelete { indexSet in
self.animals.remove(atOffsets: indexSet) // Delete "??" from animals
}
}
}
}
Thread 1: Fatal error: Index out of range
when delete item
?? has been removed from animals and the ForEach loop seems to be running twice, even though animals.count is 1.
(lldb) po animals.count
1
(lldb) po animals
? 1 element
- 0 : "??"
Please give me advice on the combination of Foreach and TextField.
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…