Reputation: 83
I'm creating an application where users can add players to a list. (Preparing for a game) but I'm kind of stuck here.
I've a textfield where I enter a player name, and tapping on a button which will add the player to the tableview. But every time I add a new player it getting replaced by the next one. So let's say I add. one player: "Player 1" and then I'm adding another player, both names will be "player 2".
I've tried to add a for-loop (Which I don't understand fully since its completely different from java, c# etc) but my idea is to add a for-loop which will loop through all indexes of the array list and then add the value.
@IBAction func addNewPlayerButtonTapped(_ sender: Any){
allPlayers.append(txtfield_player.text!)
tableView.insertRows(at: [IndexPath(row: allPlayers.count-1, section: 0)], with: .automatic)
txtfield_player.text = ""
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allPlayers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellOne", for: indexPath) as! HomeTableViewCell
cell.lbl_playerName.text = allPlayers[0..<allPlayers.count] //I'm getting error here.
return cell
}
How can I fix that? (If I had cell.lbl_playerName.text = allPlayers[0] it will only get the first index ofc) but I need something similar. So I can add like an "i" which stands for ALL indexes. Hope you understand what I mean.
I think I managed to fix the cell.lbl_playerName.text, but the problem is that ALL rows is getting replaced. So if I add another one lets say "player 3", all players will be "player 3" in the tableview.
Upvotes: 1
Views: 79
Reputation: 83
I solved the issue by doing this:
let row = indexPath.row
cell.lbl_playerName.text = allPlayers[row]
inside the cellForRow
Upvotes: 1