How to select an item by a button or tapGesture in my SwiftUI List and transfer it to another view

777 views Asked by At

In my app I´m needing two players (only 2 names/strings), selected from an array built in a List/ForEach SwiftUI-code, which are used in another view.

What is the way to bring the name into a string for my Text(item)?

Can I select two items out of the list?

Thx for any help. Franz

My code (modified, found by Ale Patron,Tutorial using UserDefaults with encoding and decoding the array/list ):

@State private var allTeams: [PlayerItem] = []
@State private var newPlayer = ""
@State private var selectedPlayer = ""

@State private var selection: String?

struct PlayerItem: Identifiable {
    var id = UUID()
    let player: String
}


var body: some View {
    VStack{
    HStack {
        TextField("Add Players/Teams...", text: $newPlayer)
            .textFieldStyle(RoundedBorderTextFieldStyle())
        
        Button(action: {
            self.allTeams.append(PlayerItem(player: self.newPlayer))
            self.newPlayer = ""
           
        }) {
            Image(systemName: "plus")
        }
        .padding(.leading, 5)
    }.padding()
    
    
    
    List{
        ForEach(allTeams) { playerItem in
            Text(playerItem.player)
        }
        .onTapGesture {
            print("How can I select my first und my second player")
        }
        
    }
       Text("Selected Player: \(selectedPlayer)")
        
    }
}

}

1

There are 1 answers

1
Infxmous On

You should use indices for what you are trying to do. Try this:

 ForEach(allTeams.indices) { i in
          Text(allTeams[i].player)
             .onTapGesture {
                print("How can I select my first und my second player")
                print("The selected player is \(allTeams[i].player). The second player is \(allTeams[i + 1].player)"
            }
        }

Make sure to also check if the selected player is the last one in the array and to catch this. Otherwise, you may encounter an out-of-bounds error.