I am trying to use confirmationDialog to delete an item in a List. But what happens is that the wrong item gets deleted. Why?
Here is my code:
struct MyView: View {
@State private var selectedUsers: MyModel?
@State var datas: [MyModel]
@State private var confirmDelete = false
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
}
.alert(isPresented: $confirmDelete) {
Alert(title: Text("title"),
message: Text("message"),
primaryButton: .destructive(Text("Delete")) {
self.delete(item: data)
},
secondaryButton: .cancel())
}
} .onDelete { (indexSet) in
self.datas.remove(atOffsets: indexSet)
}})
})}
private func delete(item data: MyModel) {
if let index = datas.firstIndex(where: { $0.id == data.id }) {
datas.remove(at: index)
}
}}