Reputation: 417
I have a view called EditEventView(), which is displayed as a sheet, and has two objects passed into it; Team
and Match Event
. Inside the match event object, I store an attribute of type Player
, these players can also be found using team.players
.
Inside this new sheet view, I have some PickerViews which should show all the players of a Team
object, the user can then select one and it's assigned to the Match Event. When I loaded into this view I wanted the @State
variable to be set to the index of these players, rather than 0, which they are set at currently. However I believe it is impossible to change these states' values inside the view, and I don't have enough knowledge of init
functions to look at this.
This is an abbreviated version of EditEventView():
struct EditEventView: View {
@ObservedObject var team: Team
@State var event: MatchEvent
@State var playerSelect = 0
var body: some View{
NavigationView{
Form{
Picker(selection: $playerSelect, label: Text("Player Off")) {
ForEach(0..<team.players.count) {
Text("\(team.players[$0].shirtNumber) - \(team.players[$0].playerName)")
}
.navigationBarTitle("Select Player Off")
}
This view is shown using:
Button(action: {self.event = event}) {
MainEventBox(event: event)
}
.sheet(item: self.$event){ event in
EditEventView(team: event.team, event: event)
}
Match Event is a struct, like this:
struct MatchEvent: Identifiable{
var id = UUID()
var team: Team
var player: Player
var eventType: eventType
}
Each Team is structured like this:
class Team: ObservableObject{
@Published var players: [Player] = [Player(playerName: "", shirtNumber: 1, active: true),
Player(playerName: "", shirtNumber: 2, active: true),
Player(playerName: "", shirtNumber: 3, active: true)....]
func findPlayer(player: Player) -> Int?{
var i: Int = 0
for x in self.players{
if x.id == player.id{
return i
}
i += 1
}
return nil
}
}
I believe that I would have to initialize the view and set the value of playerSelect
to the result of team.findPlayer(player: event.player)
. However, I'm not sure and may be completely wrong!
Any help would be appreciated!
Upvotes: 0
Views: 68
Reputation: 981
Here is how you can initialize the state var:
@ObservedObject private var team: Team
@State private var event: MatchEvent
@State private var playerSelect
init(team: Team, event: MatchEvent) {
self.team = team
self._event = State(initialValue: event)
let playerSelect = team.findPlayer(player: event.player)
self._playerSelect = State(initialValue: playerSelect)
}
Upvotes: 1