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

SwiftUI动态列表复杂元素如何实现删除?onDelete报错如何解决?

问题原因

onDelete 是 ForEach 组件的专属修饰符,不是 List 的修饰符。你当前直接将绑定数组传入 List 初始化方法,SwiftUI 隐式生成的内部 ForEach 没有开放删除相关能力,直接给 List 加 onDelete 自然会报「无该成员」的错误。

解决方案

把隐式的 ForEach 改成显式声明,将 onDelete 修饰符加到 ForEach 上即可,原有业务逻辑完全不需要修改。

修改后的核心代码如下:

@ObservedObject var dm: DataManager = DataManager.shared
@State var isAddShown = false

var body: some View {
    NavigationView {
        VStack {
            // 外层只保留List容器,内部显式声明ForEach
            List {
                ForEach($dm.TTDItemList) { $item in
                    // 原有列表项代码完全不变
                    VStack(alignment: .leading) {
                        TextEditor(text: $item.itemDesc)
                            .onTapGesture {}
                        Text(item.ItemTagsToText())
                            .font(.caption)
                            .foregroundColor(Color.red)
                            .multilineTextAlignment(.leading)
                    }
                }
                // onDelete移到ForEach上
                .onDelete(perform: cancella)
            }
        }
        .onTapGesture { hideKeyboardAndSave() }
        .navigationBarTitle(Text("Board"), displayMode: .inline)
        .navigationBarItems(trailing:
                                Button(action: { withAnimation { self.isAddShown.toggle() } }) {
            Image(systemName: !isAddShown ? "plus.circle.fill" : "minus.circle.fill").imageScale(.large)
        }
        )
    }
}

private func hideKeyboardAndSave() {
    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    dm.salva()
}

func cancella(at offset: IndexSet) {
    guard let intindex = Array(offset).first else { return }
    dm.TTDItemList.remove(at: intindex)
    dm.salva()
}

如果需要开启列表批量编辑功能,只需要在导航栏的按钮组里加上系统自带的 EditButton() 即可,不需要额外修改删除逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:09:03