我制作了一个练习应用程序,其中主视图是一个简单列表。轻按列表中的项目后,将显示详细视图。在详细信息视图中是一个“删除”按钮,用于删除该项目。
如何从详细视图中删除每个项目?
主视图:
struct ContentView: View {
@EnvironmentObject var viewModel: ViewModel
var body: some View {
NavigationView {
List {
ForEach(0 ..< viewModel.items.count, id: \.self) { index in
NavigationLink(destination: DetailView()) {
Text(self.viewModel.items[index].title)
}
}
}
.navigationBarTitle("Practice")
.navigationBarItems(trailing: Button(action: makeNew) {
Text("Add")
})
}
}
func makeNew() {
withAnimation {
viewModel.items.append(Model(title: "New Item \(viewModel.items.count + 1)"))
}
}
}
详细信息视图:
struct DetailView: View {
@EnvironmentObject var viewModel: ViewModel
var body: some View {
Button(action: remove) {
Text("Delete")
}
}
func remove(at offsets: IndexSet) {
withAnimation {
viewModel.items.remove(atOffsets: offsets)
}
}
}
模型:
struct Model: Identifiable {
var id = UUID()
var title: String
}
和ViewModel:
class ViewModel: ObservableObject {
@Published var items = [Model]()
}
答案 0 :(得分:1)
您需要在DetailView
中传递项目,例如按索引
NavigationLink(destination: DetailView(index: index)) { // << here !!
Text(self.viewModel.items[index].title)
}
因此,可以按索引删除
struct DetailView: View {
@EnvironmentObject var viewModel: ViewModel
let index: Int
var body: some View {
Button("Delete") {
self.remove(at: IndexSet(integer: self.index)) // << here !!
}
}
func remove(at offsets: IndexSet) {
withAnimation {
viewModel.items.remove(atOffsets: offsets)
}
}
}