Add item to list

I have an app with 2 swiftui files and one swift file.

The swift file contains my data array. File 1 has the contentview for my list, and file 2 contains the row view. I added a button to add data to my list however when I call the function it does not add it to the list. I hope this make sense I have included the code:

Swiftfile

struct PlayerInfo: Identifiable  {
    var id = UUID()
    var playerName: String
    var playerPosition: String
    var goals: Int
    var assists: Int
    var points: Int
}

var playerData: [PlayerInfo] = [
    PlayerInfo(playerName: "Artemi Panarin", playerPosition: "LW", goals: 29, assists: 63, points: 92)]


Swift contentview file: 

struct RosterView: View {
    
    
    
    var body: some View {
        NavigationView {
            
            List {
                ForEach(playerData) { player in
                    
                    PlayerRow(player: player)
                }
            }        .navigationBarTitle("Rangers Stats", displayMode: .inline)
                .navigationBarItems(trailing: Button("Add", action: addItemToRow))
        }

    }
    func addItemToRow() {
        playerData.append(PlayerInfo(playerName: "Joe Miehl", playerPosition: "C", goals: 5, assists: 5, points: 10))

    }
}


#Preview {
    RosterView()
}

import SwiftUI

struct PlayerInfo: Identifiable  {
  var id = UUID()
  var playerName: String
  var playerPosition: String
  var goals: Int
  var assists: Int
  var points: Int
}

struct ContentView: View {

 @State private var playerData: [PlayerInfo] = []

  var body: some View {
    NavigationStack {
      List(playerData) { player in
        PlayerRow(player: player)
      }
      .toolbar {
        ToolbarItem {
          Button("Add", action: addPlayers)
        }
      }
    }
  }

  func addPlayers() {
    let newPlayers: [PlayerInfo] = [
        PlayerInfo(playerName: "Artemi Panarin", playerPosition: "LW", goals: 29, assists: 63, points: 92),
        PlayerInfo(playerName: "Panarin Artemi", playerPosition: "LW", goals: 29, assists: 63, points: 92)
    ]
    playerData.append(contentsOf: newPlayers)
  }
}


#Preview {
  ContentView()
}

Something like this :slight_smile:

@linas-ios

Hi Linas,

When you post code in a reply, you need to format it by selecting that code block and tap the </> icon in the editing toolbar at the top of the window as indicated by the arrow in the following screen shot.

I fixed it :upside_down_face:

1 Like

@linas-ios

Thank you, your suggestion does allow me to add a new player. However it eliminates my previous list of players. Would you be able to suggest a change that adds my new player to the bottom of the list?

Appreciate any help you can provide I am a newbie trying to develop my skills further

In the suggested solution, there is no previous data. playerData is initialized with an empty array.

Add some code before you display the list to put some initial data into playerData.