更改特定列表元素的颜色SwiftUI [英] Changing the colour of specific list elements SwiftUI

查看:73
本文介绍了更改特定列表元素的颜色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.

每个Player对象都有一个.active属性,该属性为true或false.根据此值,我希望该行的背景为浅灰色,而不是其他背景的白色.我该怎么做?我希望它会像这样简单:

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

推荐答案

可以使用 listRowBackground 修饰符来实现(但您需要使用 ForEach 而不是直接列出).

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

这篇关于更改特定列表元素的颜色SwiftUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆