SwiftUI:如何根据card.owned值动态设置List行背景颜色
SwiftUI List 按条件设置行背景色
你当前的代码把.listRowBackground应用到了遍历sections的外层ForEach上,导致所有Section的行都被统一设置为lightGreen背景。要实现仅card.owned > 0的行变色,需要把背景修饰符移到单个行元素上,并添加条件判断。
修改后的代码如下:
List { ForEach(cards) { section in let header: String = nameForSectionHeader(sectionID: section.id) Section(header: Text(header)) { ForEach(section) { card in NavigationLink(destination: CardView(card: card)) { VStack(alignment: .leading) { if let name = card.name, let id = card.cardID { Text("\(id) - \(name)") } if let set = card.set, let setName = set.name { Text("Set: \(setName)") } if card.owned > 0 { Text("Owned: \(card.owned)") } } } // 针对每行做条件背景设置 .listRowBackground(card.owned > 0 ? lightGreen : Color(UIColor.systemBackground)) } } } }
关键改动说明:
- 移除了外层
ForEach的.listRowBackground,避免全局应用背景色。 - 在内部
ForEach的NavigationLink上添加条件式背景修饰:- 当
card.owned > 0时,使用自定义的lightGreen背景。 - 否则,用
Color(UIColor.systemBackground)匹配系统默认的列表行背景色,自动适配明暗模式。
- 当
内容的提问来源于stack exchange,提问作者Ceri Turner
相关产品推荐
相关产品推荐

