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

SwiftUI结合Core Data如何在ForEach循环中通过删除按钮删除对应条目

解决方案

有两种实现方式,你可以根据需求选择:

方案1:适配现有deleteItems方法,通过索引删除

遍历FetchedResults时同时获取索引和对应条目,点击时把当前索引封装为IndexSet传入原有删除方法即可,核心修改点如下:

// 把原来的ForEach替换为以下代码,同时拿到索引和prod对象
ForEach(Array(products.enumerated()), id: \.element) { index, prod in
    let prodItems = Product(name: prod.name ?? "Undefined", price: prod.price ?? "Undefined", type: "type", brand: prod.brand ?? "Undefined", images: [prod.image!,""])
    ZStack {
        Cells(product: prodItems)
        Button(action: {
            // 直接传入当前索引即可
            deleteItems(offsets: IndexSet(integer: index))
        }) {
            Image(systemName: "xmark.bin.circle")
                .resizable()
                .frame(width: 30, height: 30)
                .foregroundColor(.red)
                .background(.black)
                .clipShape(RoundedRectangle(cornerRadius: 20))
                .offset(x: 60, y: 45)
        }
    }
}

注意:你的@FetchRequest目前没有设置排序规则,可能会导致FetchedResults顺序随机变化,建议至少添加一个排序字段,避免索引匹配错误,示例:

@FetchRequest(
    sortDescriptors: [NSSortDescriptor(keyPath: \Prod.name, ascending: true)], 
    animation: .default) 
private var products: FetchedResults<Prod>

方案2:直接删除当前Core Data对象(更稳妥,无需计算索引)

Core Data支持直接删除指定的托管对象,无需通过索引查找,你可以新增一个单条删除方法,实现更简单,出错概率更低:

// 新增单条删除方法
private func deleteSingleItem(prod: Prod) {
    withAnimation {
        viewContext.delete(prod)
        do {
            try viewContext.save()
        } catch {
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    }
}

// 按钮的action直接调用即可
Button(action: {
    deleteSingleItem(prod: prod)
}) {
    // 按钮样式保持不变
}

内容的提问来源于stack exchange,提问作者Fovu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:54:08