SwiftUI:如何通过列表项内的按钮删除对应列表元素?
实现点击列表项内按钮删除对应项的方案
方案一:通过索引删除
直接遍历数组的indices获取元素位置,就能在按钮点击时精准删除对应项,适配单个删除操作的场景:
修改后的ForEach代码:
ForEach(items.indices, id: \.self) { index in let current = items[index] VStack(alignment: .leading) { Text(current.task) .padding(2) Text(dateFormatter.string(from: current.date)) Button(action: { items.remove(at: index) }, label: { Image(systemName: "checkmark.rectangle.fill") .resizable() .frame(width: 50, height: 35) }) } }
方案二:利用Hashable特性过滤数组
因为Tasks已经实现Hashable,可以直接过滤数组移除当前点击的元素,无需处理索引,代码更简洁:
修改后的ForEach代码:
ForEach(items, id: \.self) { current in VStack(alignment: .leading) { Text(current.task) .padding(2) Text(dateFormatter.string(from: current.date)) Button(action: { items = items.filter { $0 != current } }, label: { Image(systemName: "checkmark.rectangle.fill") .resizable() .frame(width: 50, height: 35) }) } }
场景适配说明
- 如果存在完全重复的
Tasks实例(task和date均相同),方案二会删除所有重复项,此时方案一更合适; - 若所有
Tasks实例唯一,方案二的无索引写法更安全,能避免索引越界风险。
内容的提问来源于stack exchange,提问作者Halas Wolff
相关产品推荐
相关产品推荐

