I have list items in SwiftUI, and when I delete list items, but when I click the delete button, it delete item randomly, I want to delete seleted item, where is the mistake?
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
}
.confirmationDialog( "Are you sure ?",
isPresented: $confirmDelete,
titleVisibility: .visible
){
Button(role: .destructive) {
self.delete(item: data)
} label: {
Text("ok")
}
Button(role: .cancel) {
} label: {
Text("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)
}
}}