简体   繁体   中英

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. 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).

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))
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM