Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete Array Row With .contextMenu

I want to delete a row from keydata if a user uses the .contextMenu { }, here "Hello World löschen".

@State private var keyData = [
    ListView("1", "Hello", "World"),
    ListView("2", "Bye", "Wold")
]

enter image description here

ForEach($keyData) { $i in
    NavigationLink()) {
        //
    }
    .contextMenu {
        Button { } // ?
        label: {
            Text(i.firstName) +
            Text(" ") +
            Text(i.lastName) +
            Text(" löschen")
        }
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need the index to delete the item you want to remove (efficiently). Change your ForEach:

ForEach(Array(keyData.enumerated()), id: \.element) { (index, element) in
    NavigationLink("test", destination: Text("test"))
    .contextMenu {
        Button {
            keyData.remove(at: index)
        } label: {
            Text(element.firstName) +
            Text(" ") +
            Text(element.lastName) +
            Text(" löschen")
        }
    }
}

And you can replace any $i bindings with $keyData[index].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading