You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:31:00