【发布时间】:2020-07-15 21:13:38
【问题描述】:
我正在制作一个练习应用程序,其中主视图是一个底部带有按钮的列表。按下按钮将项目添加到列表中。当点击该项目时,它会显示在视图中间有一个按钮的详细视图。
我想要做的是,当按下按钮时,它会从列表中删除项目并将我移回主视图。我的问题是对按钮实现删除功能时出错。
错误是这样的:无法将类型'(IndexSet) -> ()'的值转换为预期的参数类型'() -> Void'
我该如何解决?
这是主视图:
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]()
}
【问题讨论】:
-
我认为你需要将IndexSet参数传递给removeRecoding函数