You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

关键改动说明:

  1. 移除了外层ForEach的.listRowBackground,避免全局应用背景色。
  2. 在内部ForEach的NavigationLink上添加条件式背景修饰:
    • 当card.owned > 0时,使用自定义的lightGreen背景。
    • 否则,用Color(UIColor.systemBackground)匹配系统默认的列表行背景色,自动适配明暗模式。

内容的提问来源于stack exchange,提问作者Ceri Turner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:24:27