Replicate delete note with alert confirmation in swiftUI as Notes app

83 Views Asked by At

I am trying to mimic the same behaviour that notes app does when deletes a note in swiftUI. I have this code, but I am still missing the delete button to expand to cover the width of the cell.

import SwiftUI

struct ItemStore {
    var items: [String]
}
struct ContentView: View {
    let itemStore = ItemStore(items: [
        "Hi",
        "Hello"
    ])
    @State var showingAlert = false


    
    var body: some View {
        List {
            ForEach(itemStore.items, id: \.self) { item in
                Text("Item: \(item)")
                    .swipeActions() {
                        Button {
                            withAnimation { showingAlert.toggle() }
                        } label: {
                            Label("Delete", systemImage: "trash")
                        }
                    }
                    .tint(.red)
                
            }
        } /// alert goes here!
        .alert("Important message", isPresented: $showingAlert) {
            Button("First") { }
            Button("Second") { }
        }
    }
}

enter image description here

1

There are 1 best solutions below

1
ChrisR On

this should work fine, also with the animations

struct ItemStore {
    var items: [String]
    
    mutating func delete(item: String) {
        items.removeAll(where: {$0 == item})
    }
}

struct ContentView: View {
    
    @State private var itemStore = ItemStore(items: [
        "Item 1 Hi ",
        "Item 2 Hello",
        "Item 3 Ola",
    ])

    @State var showingAlert = false
    @State var deleteItem: String?

    var body: some View {
        List {
            ForEach(itemStore.items, id: \.self) { item in
                Text("Item: \(item)")
                    .swipeActions(allowsFullSwipe: true) {
                        Button {
                            deleteItem = item
                            showingAlert = true
                        } label: {
                            Label("Delete", systemImage: "trash")
                        }
                        .tint(.red)
                    }
                
            }
        }
        
        .confirmationDialog("Do you really want to delete?", isPresented: $showingAlert, titleVisibility: .visible, presenting: deleteItem, actions: { item in
            Button("Delete note", role: .destructive) {
                withAnimation {
                    itemStore.delete(item: item)
                }
            }
        })
    }
}