【问题标题】:how is possible deleting complex items in a dynamic list in SwiftUI?如何在 SwiftUI 中删除动态列表中的复杂项目?
【发布时间】:2021-09-22 14:18:57
【问题描述】:

我正在尝试为元素列表实现删除功能,但 onDelete 事件没有按预期工作。

代码如下:

    
    @ObservedObject var dm: DataManager = DataManager.shared
    @State var isAddShown = false
    
    var body: some View {
        NavigationView {
            VStack {
                List($dm.TTDItemList) { $item in
                    VStack(alignment: .leading) {
                        TextEditor(text: $item.itemDesc)
                            .onTapGesture {}
                        Text(item.ItemTagsToText())
                            .font(.caption)
                            .foregroundColor(Color.red)
                            .multilineTextAlignment(.leading)
                    }
                    
                }
                .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()
    }
    
    
}

我收到的错误是:

'List, UUID, VStack>>>' 类型的值(又名 'List , UUID, VStack>>>') 没有成员'onDelete'

实现列表很棘手,但代码似乎可以在数据管理器中保存修改。

【问题讨论】:

  • onDelete 用于ForEach 而不是List

标签: swiftui swiftui-list


【解决方案1】:

The onDelete modifier is a method of ForEach.。它没有为其他Views 定义,例如List。您需要修改您的代码以在您的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(perform: cancella)
            }

从技术上讲,onDeleteDynamicViewContent 协议的扩展方法,但符合DynamicViewContent 的唯一类型是ForEachForEach 的修改派生类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 2021-08-01
    • 2015-12-09
    相关资源
    最近更新 更多