问题
I have a list of 'players' in my app, and I want to some of them to have a different background colour depending on their properties.
Every Player object has a .active property that is either true or false. Depending on this value I want the background of that row to be a light grey rather than the white of the others. How would I do this? I was hoping it would be as simple as:
List(homeTeam.players) {player in
HStack{
Text("\(player.shirtNumber) - \(player.playerName)")
Spacer()
Text("\(player.timerText)")
}
}
回答1:
It is possible to achieve with listRowBackground modifier (but you need to use ForEach instead of List directly).
List {
ForEach(homeTeam.players) {player in
HStack{
Text("\(player.shirtNumber) - \(player.playerName)")
Spacer()
Text("\(player.timerText)")
}
.listRowBackground(player.active ? Color(UIColor.lightGray) :
Color(UIColor.systemBackground))
}
}
来源:https://stackoverflow.com/questions/64942527/changing-the-colour-of-specific-list-elements-swiftui