[英]Changing the colour of specific list elements SwiftUI
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.每个 Player 对象都有一个 true 或 false 的 .active 属性。 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)")
}
}
It is possible to achieve with listRowBackground
modifier (but you need to use ForEach
instead of List
directly).可以使用
listRowBackground
修饰符来实现(但您需要直接使用ForEach
而不是List
)。
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))
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.