Changing the colour of specific list elements SwiftUI

梦想的初衷 提交于 2021-01-05 09:11:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!