I have a simple app in SwiftUI, and I try to delete all list items with context menu , when I click context menu button, I want to remove all items, is it possible?
struct MyView: View {
@State private var selectedUsers: MyModel?
var body: some View {
ScrollView(.vertical, showsIndicators: false, content: {
VStack(content: {
ForEach(datas){ data in
MyRowView(data: data)
.contextMenu {
Button(action: {
self.delete(item: data)
}) {
Text("delete")
}
}
.onTapGesture {
selectedUsers = data
}
} .onDelete { (indexSet) in
selectedUsers.remove(atOffsets: indexSet)
}})
})}
private func delete(item data: MyModel) {
if let index = datas.firstIndex(where: { $0.id == data.id }) {
datas.remove(at: index)
}
}}
model:
struct MyModel: Identifiable, Hashable, Codable {
var id = UUID().uuidString
var name: String
}
var datas = [
MyModel(name: "david"),
MyModel(name: "marry"),
]