I'm trying to get the array listaDeJugadores to be used in all my views. I am able to add a Player to it and its name and age. However, when I try to display it in the view called otherPage, it gives me an error, thread 1: Fatal error: Index out of range. I also want to be able to save the array listaDeJugadores with app Storage, however, I don't know if it's possible to use app Storage in this case. Any help will be appreciated! Thank you!.
import SwiftUI
class Todo: ObservableObject {
class Player {
var name = ""
var age = 0
}
@Published var listaDeJugadores: [Player] = []
}
struct ContentView: View {
class Player {
var name = ""
var age = 0
}
@State var index = 0
@StateObject var lista = Todo()
@State var playerName = ""
@State var firstView = true
@State var secondView = false
@State var agePlayer = 0
var body: some View {
if firstView == true {
VStack {
ZStack{
Color.pink
TextField("Player name", text: $playerName)
}
.frame(width: 350, height: 50)
.cornerRadius(25)
ZStack{
Color.pink
TextField("Player Age", value: $agePlayer, format: .number)
}
.frame(width: 350, height: 50)
.cornerRadius(25)
Button(action: {
lista.listaDeJugadores.append(Todo.Player())
lista.listaDeJugadores[index].name = playerName
lista.listaDeJugadores[index].age = agePlayer
playerName = ""
index += 1
}, label: {
ZStack{
Color.black
Text("Add")
.font(.title)
.foregroundColor(Color.white)
}
.frame(width: 350, height: 50)
.cornerRadius(25)
})
Button(action: {
firstView = false
secondView = true
}, label: {
ZStack{
Color.black
Text("Done")
.font(.title)
.foregroundColor(Color.white)
}
.frame(width: 350, height: 50)
.cornerRadius(25)
})
}
} else if secondView == true {
otherPage()
.environmentObject(Todo())
}
}
}
struct otherPage: View {
@EnvironmentObject var lista: Todo
var body: some View {
Text("\(lista.listaDeJugadores[0].name)")
}
}