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

如何在SwiftUI List中设置选中行的背景颜色

SwiftUI List修改选中行背景色实现方案

你当前使用PlainListStyle的默认选中背景为系统灰色,效果如下:
选中行背景颜色

下面给出两种常用实现方案:

方案1:全局生效(兼容iOS 13+)

通过修改UITableViewCell的全局外观实现,不需要改动原有List业务代码:

// 建议放在App的初始化方法中,或者当前页面的onAppear修饰符内
UITableViewCell.appearance().selectedBackgroundView = {
    let bgView = UIView()
    bgView.backgroundColor = .systemMint // 替换为你需要的选中背景色
    return bgView
}()

方案2:仅当前页面生效(兼容iOS 15+,纯SwiftUI实现)

通过绑定选中状态,配合listRowBackground修饰符自定义单页面的选中样式:

  1. 首先定义选中状态变量:
@State private var selectedRecipe: Recipe? // 将Recipe替换为你实际的数据模型类型
  1. 修改原有List代码:
List(selection: $selectedRecipe) {
    ForEach(recipesToShow, id: \.self) { recipe in
        NavigationLink(
            destination: RecipeDetailWrapper(recipe: recipe),
            tag: recipe,
            selection: $selectedRecipe
        ) {
            RecipeListRow(recipe: recipe)
                .environmentObject(recipeDateFormatter)
        }
        // 自定义选中/未选中状态的行背景
        .listRowBackground(selectedRecipe == recipe ? Color.yellow : Color.clear)
    }
    .onDelete(perform: deleteRecipe)
}
.listStyle(PlainListStyle())

补充说明

  • 全局修改方案会影响App内所有List的选中样式,如果不同页面需要不同的选中色,优先使用方案2
  • 如果你的自定义Row内部已经设置了背景色,需要调整listRowBackground的颜色透明度或者优先级,避免被覆盖
  • iOS 16及以上版本使用NavigationStack时,上述两种方案都可以正常兼容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:54:05