SwiftUI-从过滤列表中删除项目

时间:2020-05-14 18:50:40

标签: swiftui

我有一个过滤列表,我需要使用ForEach的.onDelete方法删除项目。由于delete(at offsets:IndexSet)函数使用当前显示列表的索引,因此我需要完全参考列表项的此顺序。

不幸的是,当我想引用对filteredTools变量的引用时,出现以下错误:

不能对不可变值使用变异成员:“ filteredTools”是仅获取属性

有什么办法解决这个问题吗?

谢谢!

struct ToolList: View {
    @EnvironmentObject var userData: UserData
    @State var showingFilter = false
    @State var editMode = EditMode.inactive

    var toolCategories: [String: [Tool]] {
        Dictionary(
            grouping: userData.tools,
            by: { $0.category }
        )
    }

    var filteredTools: [Tool] {
        var list = [Tool]()
        for category in self.userData.selectedToolCategories {
            if category.isSelected && self.toolCategories[category.name] != nil {
                list += self.userData.showFavoritesOnly ? self.toolCategories[category.name]!.filter { $0.isFavorite } : self.toolCategories[category.name]!
            }
        }
        return list
    }

    var body: some View {
        NavigationView {
            List {
                ForEach(filteredTools) { tool in
                    NavigationLink(destination: ToolDetail(tool: tool).environmentObject(self.userData)) {
                        ToolRow(tool: tool)
                    }
                }
                .onDelete(perform: delete)
            }
            .navigationBarTitle(Text(NSLocalizedString("Tools", comment: "")))
            .navigationBarItems(
                leading: EditButton(),
                trailing: NavigationBar(showingFilter: self.$showingFilter, editMode: self.$editMode)
                    .environmentObject(userData)
            )
            .environment(\.editMode, $editMode)
            .sheet(isPresented: $userData.showingProfile) {
                ProfileHost()
                    .environmentObject(self.userData)
            }
            .sheet(isPresented: $showingFilter) {
                FilterView(isPresented: self.$showingFilter, categories: self.$userData.selectedToolCategories)
            }
        }
    }

    func delete(at offsets: IndexSet) {
        self.filteredTools.remove(atOffsets: offsets) // <-- this is where I get this error message: Cannot use mutating member on immutable value: 'filteredTools' is a get-only property
    }
}

1 个答案:

答案 0 :(得分:0)

我通过在模型中而不是视图中实现删除功能,通过传递实际显示(过滤的)列表来确定要删除的项目的ID以及项目的索引来解决该问题:

private func onDelete(offsets: IndexSet) {
    userData.delete(from: filteredTools, offsets: offsets)
}