如何解决尝试从列表中删除项目的按钮错误?

时间:2020-07-15 21:13:38

标签: swift list mvvm swiftui

我正在制作一个练习应用程序,其中主视图是一个列表,底部带有一个按钮。按下按钮可将一个项目添加到列表中。点按该项目时,将显示详细视图,该视图在视图的中间具有一个按钮。

我想做的是,当按下按钮时,它会删除列表中的项目并将我移回主视图。我的问题是,对按钮实施删除功能时出现错误。

错误是这样的:无法将类型'((IndexSet)->()'的值转换为预期的参数类型'()->空'

我该如何解决?

这是主视图:

struct ContentView: View {
    @EnvironmentObject var store: CPStore
    
    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(0..<store.items.count, id:\.self) { index in
                        NavigationLink(destination: Detail(index: index)) {
                            VStack {
                                Text(self.store.items[index].title)
                            }
                        }
                    }
                }
                Spacer()
                
                Button(action: {
                    self.add()
                }) {
                    ZStack {
                        Circle()
                        .frame(width: 87, height: 87)
                    }
                }
            }
            .navigationBarTitle("Practice")
        }
    }
    
    func add() {
        withAnimation {
            store.items.append(CPModel(title: "Item \(store.items.count + 1)"))
        }
    }
}

这是详细视图:

struct Detail: View {
    @EnvironmentObject var store: CPStore
    @Environment(\.presentationMode) var presentationMode
    let index: Int
    
    var body: some View {
        Button(action: removeRecording) { // <- I got the error here
            Image(systemName: "trash")
        }
        .foregroundColor(.blue)
        .font(.system(size: 24))
    }
    
    func removeRecording(at offsets: IndexSet) {
        withAnimation {
            store.items.remove(atOffsets: offsets)
            self.presentationMode.wrappedValue.dismiss()
        }
    }
}

模型:

struct CPModel: Identifiable {
    var id = UUID()
    var title: String
}

和ViewModel:

class CPStore: ObservableObject {
    @Published var items = [CPModel]()
}

1 个答案:

答案 0 :(得分:1)

我指的是这个post

更新您的removeRecording函数

func removeRecording(at offsets: IndexSet) -> () -> () {
        return {
            withAnimation {
                store.items.remove(atOffsets: offsets)
                self.presentationMode.wrappedValue.dismiss()
            }
        }
    }

并更改按钮以传递参数

Button(action: removeRecording(at: [index]))