如果我希望在编辑模式下删除列表中的数组项,似乎没有问题。 但是说到字典,我根本就拿不掉这个项目。
struct ExploringEditButton2: View {
// private var users = ["Paul", "Taylor", "Adele"]
@State private var users = ["A": "1", "B": "2"]
var body: some View {
NavigationView {
List {
ForEach(Array(users.keys), id: \.self) { key in
Text(key)
}
.onDelete(perform: deleteOnKey)
}
.navigationBarItems(trailing: EditButton())
}
}
func deleteOnKey(key: String, user: [String:String]){
user[key] = nil //Cannot assign through subscript: 'user' is a 'let' constant
}
func deleteListItem(at offsets: IndexSet) {
print("offsets : \(offsets)")
users.remove(atOffsets: offsets)
}
}
知道这里出了什么问题吗?
更新的答案:
我重写了deleteListItem函数。 现在起作用了。
func deleteListItem(at offset: IndexSet) {
print("offset \(offset) offset.first! : \(offset.first!)")
// let key = Array(self.users.keys)[offset.first!]
let key = Array(users.keys)[offset.first!]
self.users.removeValue(forKey: key)
}
这是一个有效的解决方案。 使用Xcode 11.4/iOS 13.4进行测试
struct ExploringEditButton2: View {
// private var users = ["Paul", "Taylor", "Adele"]
@State private var users = ["A": "1", "B": "2"]
var body: some View {
NavigationView {
List {
self.listContent(for: Array(users.keys))
}
.navigationBarItems(trailing: EditButton())
}
}
private func listContent(for keys: [String]) -> some View {
ForEach(keys, id: \.self) { key in
Text(key)
}
.onDelete { indexSet in
let key = keys[indexSet.first!]
self.users.removeValue(forKey: key)
}
}
}