Home > Software engineering >  How we can use alert menu before delete list items in SwiftUI?
How we can use alert menu before delete list items in SwiftUI?

Time:02-28

I have list items in SwiftUI, and when I delete list items I want to delete after alert menu, like

"do want to delete your list items, ""yes" or "no"

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
                       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)
               }
           }}

CodePudding user response:

In the delete action you set a @State bool to true, this triggers e.g. a ConfirmationDialog – and only after confirming there, you really delete:

           } .onDelete { (indexSet) in
                confirmDelete = true      // a @State var Bool
            }})
            .confirmationDialog("Do you really want to delete?", isPresented: $confirmDelete) {
                Button("Delete", role: .destructive) {
                    selectedUsers.remove(atOffsets: indexSet)
                }
                Button("Cancel", role: .cancel) { }
            }
  • Related