我有一个包含按钮列表的视图,每个按钮代表一个玩家。我的目标是在按下他们各自的按钮时将他们添加到团队中。
struct AddPlayers: View {
var team: Team
var playerData = getPlayers()
var body: some View {
List(playerData) { player in
Button(action: {
addPlayerToTeam(teamID: team.id, playerID: player.id)
// update the PlayerRow to show player was added to team
}) {
PlayerRow(player: player, team: self.team)
}
}
.navigationBarTitle(Text("Players"))
}
}
struct PlayerRow: View {
var player: Player
var team: Team
var body: some View {
let view = HStack {
Text(verbatim: player.FirstName)
Text(verbatim: player.LastName)
Spacer()
// displays true if player is on the team
if playerInTeam(team: team, player: player) {
Text("True")
}
}
return view
}
}
按下后,我可以将玩家添加到团队中,但是我还没有弄清楚如何更新UI。当前,如果我关闭该应用程序并重新打开它以强制重新加载UI,那么它将在正确的播放器上显示“ True”。
我尝试将playerData
设置为@State
变量,并在每次按下按钮时更新playerData
。这将导致行PlayerRow(player: player, team: self.team)
运行,但是PlayerRow
的正文从未输入,因此UI不会更新。
struct AddPlayers: View {
var team: Team
@State var playerData = getPlayers()
var body: some View {
List(playerData) { player in
Button(action: {
addPlayerToTeam(teamID: team.id, playerID: player.id)
// attempt to force reload the List
playerData = getPlayers()
}) {
// called due to playerData = getPlayers()
PlayerRow(player: player, team: self.team)
}
}
.navigationBarTitle(Text("Players"))
}
}
struct PlayerRow: View {
// this sections is run due to playerData = getPlayers()
var player: Player
var team: Team
var body: some View {
// code does not enter here
let view = HStack {
Text(verbatim: player.FirstName)
Text(verbatim: player.LastName)
Spacer()
// displays true if player is on the team
if playerInTeam(team: team, player: player) {
Text("True")
}
}
return view
}
}
感谢所有帮助!