0

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

1 Answer 1

1

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].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.