下面的代码在删除TextField()时抛出索引超出范围错误,但在删除Text()时不会抛出索引超出范围。
这是完整的错误:致命错误:索引超出范围:文件Swift / ContiguousArrayBuffer.swift,第444行
import SwiftUI
struct Information: Identifiable {
let id: UUID
var title: String
}
struct ContentView: View {
@State var infoList = [
Information(id: UUID(), title: "Word"),
Information(id: UUID(), title: "Words"),
Information(id: UUID(), title: "Wording"),
]
var body: some View {
Form {
ForEach(0..<infoList.count, id: \.self){ item in
Section{
// Text(infoList[item].title) //<-- this doesn't throw error when deleted
TextField(infoList[item].title, text: $infoList[item].title)
}
}.onDelete(perform: deleteItem)
}
}
private func deleteItem(at indexSet: IndexSet) {
self.infoList.remove(atOffsets: indexSet)
}
}
答案 0 :(得分:0)
@Asperi's response about creating a dynamic container是正确的。我只需要进行一些调整,使其与Identifiable兼容。最终代码如下:
import SwiftUI
struct Information: Identifiable {
let id: UUID
var title: String
}
struct ContentView: View {
@State var infoList = [
Information(id: UUID(), title: "Word"),
Information(id: UUID(), title: "Words"),
Information(id: UUID(), title: "Wording"),
]
var body: some View {
Form {
ForEach(0..<infoList.count, id: \.self){ item in
EditorView(container: self.$infoList, index: item, text: infoList[item].title)
}.onDelete(perform: deleteItem)
}
}
private func deleteItem(at indexSet: IndexSet) {
self.infoList.remove(atOffsets: indexSet)
}
}
struct EditorView : View {
var container: Binding<[Information]>
var index: Int
@State var text: String
var body: some View {
TextField("", text: self.$text, onCommit: {
self.container.wrappedValue[self.index] = Information(id: UUID(), title: text)
})
}
}