[英]SwiftUi I can not delete item
我不明白為什么會發生錯誤。 addItem()
可以工作,但是在執行removeItem()
時發生錯誤。
我的視圖模型
class MyViewModel: ObservableObject {
@Published var items:[MyModel] = []
}
我的模型
struct MyModel : Identifiable {
var id: Int
var title:String
var value:String
}
內容視圖
struct ContentView: View {
@StateObject var model = MyViewModel()
var body: some View {
VStack {
Button(action: {
addItem()
}) {
Text("add")
}
ForEach(0..<model.items.count, id: \.self) { index in
HStack {
TextField("value", text: Binding(get: { self.model.items[index].value },
set: { self.model.items[index].value = $0 }))
Button(action: {
removeItem()
}) {
Text("delete")
}
}
}
}
}
func addItem() {
self.model.items.append(MyModel(id: +1, title: "", value: ""))
}
func removeItem() {
if let index = model.items.first?.id {
model.items.remove(at: index)
}
}
}
我認為問題出在func removeItem()
問題出在ForEach
正如蘋果文檔中提到的
ForEach
:實例只讀取提供數據的初始值,不需要跨更新識別視圖。
因此,當您從數組中刪除一個對象時,您已經更改了數組,但 SwiftUI 沒有看到該更改並且它使用原始數組。
因此,您只需添加諸如index < self.model.items.count ? self.model.items[index].value : ""
類的條件即可修復它index < self.model.items.count ? self.model.items[index].value : ""
index < self.model.items.count ? self.model.items[index].value : ""
另外,我建議在ForEach
使用.indices
還有一點,您無需每次刪除時都查找索引。 只需將索引傳遞給函數。
這是完整的代碼。
struct ContentView: View {
@StateObject var model = MyViewModel()
var body: some View {
VStack {
Button(action: {
addItem()
}) {
Text("add")
}
ForEach(model.items.indices, id:\.self) { index in //< -- Here
HStack {
TextField("value", text: Binding(get: { index < self.model.items.count ? self.model.items[index].value : "" }, //<-- Here
set: { self.model.items[index].value = $0 }))
Button(action: {
removeItem(at: index) //< -- Here
}) {
Text("delete")
}
}
}
}
}
func addItem() {
self.model.items.append(MyModel(title: "", value: ""))
}
func removeItem(at index: Int) {
model.items.remove(at: index) //< -- Here
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.