I have a view where I'm displaying an array of data in a List through a Grid layout. Now, as I'd like to use the app both on MacOs and iPad, I have added a trash button to delete items in the list, but I don't know how to make it work.
Here the code I have:
import SwiftUI
struct RosaView: View {
@State var rosa: [Rosa] = Rosa.testRosa()
var stagione: String = "2023/2024"
var body: some View {
var rosaFiltrata: [Rosa] {
Rosa.testRosa().filter {
$0.stagione == stagione
}
}
var RosaGiocatori = rosaFiltrata.sorted{$0.ruoloGiocatore > $1.ruoloGiocatore}
VStack(alignment: .leading) {
Text("Stagione: \(stagione)")
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.font(.headline)
.foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
.padding()
ScrollView(.vertical) {
List {
Grid(alignment: .leading) {
GridRow {
Text("Nome")
Text("Cognome")
Text("Ruolo")
Text("Data di nascita")
Text("Età")
}
.bold()
Divider()
ForEach (RosaGiocatori, id: \.self) { giocatore in
GridRow {
Text(giocatore.nomeGiocatore)
Text(giocatore.cognomeGiocatore)
Text(giocatore.ruoloGiocatore)
Text(giocatore.nascitaGiocatore)
Text(giocatore.etàGiocatore, format: .number)
}
.scaledToFit()
}
}
}
.scrollContentBackground(.hidden)
.frame(width: 600, height: 300)
}
}
.toolbar {
ToolbarItem {
Button(action: cancellaGiocatore) {
Label("Delete Item", systemImage: "trash")
.foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
}
}
}
.navigationTitle("Rosa")
}
private func cancellaGiocatore() {
withAnimation {
print("Bottone cliccato")
}
}
}
Now, I tried several ways to select one row of the grid and delete the corresponding values, but not able to achieve any valuable result.
How can I handle this?
Thanks, A.