You need to enable JavaScript to run this app. 如何自定义修改SwiftUI中Picker选择视图与表单行的颜色?
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义修改SwiftUI中Picker选择视图与表单行的颜色?

解决方案

你遇到的点击Picker行变黑、二级选择页背景黑色、返回后颜色残留的问题,都可以通过补充全局UIKit样式配置、补全Picker必要参数解决,修改后代码如下:

struct SeafoodFilterView: View {
    
    // TestData
    var seafoods = ["Atlantic Salmon", "Atlantic Lobster", "Jumbo Sea Scallops", "Chilean Sea Bass"]
    
    @State private var selectedSeafood = ""
    
    init() {
        // 全局配置表单/列表通用样式
        let tableViewAppearance = UITableView.appearance()
        tableViewAppearance.backgroundColor = .clear
        tableViewAppearance.separatorColor = UIColor.white
        tableViewAppearance.showsVerticalScrollIndicator = false
        
        // 配置cell选中态背景,解决点击后变黑、返回残留黑色问题
        let cellAppearance = UITableViewCell.appearance()
        cellAppearance.backgroundColor = .clear
        let selectedBgView = UIView()
        selectedBgView.backgroundColor = UIColor(Color.pacificBlueAccent.opacity(0.8)) // 可替换为你需要的选中高亮色
        cellAppearance.selectedBackgroundView = selectedBgView
        
        // 配置全局列表父视图背景,解决二级选择页背景黑色问题
        UIScrollView.appearance().backgroundColor = UIColor(Color.pacificBlue)
    }
    
    var body: some View {
        NavigationView {
            ZStack {
                Color.pacificBlue
                    .edgesIgnoringSafeArea(.all)
                Form {
                    Picker(selection: $selectedSeafood, label: Text("Seafood").font(.custom(Fonts.gse, size: 18)).fontWeight(.semibold).foregroundColor(.white)) {
                        ForEach(0 ..< seafoods.count, id: \.self) {
                            Text(self.seafoods[$0])
                                .foregroundColor(.white) // 自定义选项文本颜色
                                .tag(self.seafoods[$0]) // 必须加tag才能正常绑定选中值
                        }
                    }
                    .listRowBackground(Color.pacificBlueAccent)
                }
                .scrollContentBackground(.hidden) // iOS16+ 隐藏系统默认列表背景,兼容新系统
            }
            .navigationTitle("Filters")
            .navigationBarTitleDisplayMode(.inline)
            // 下方导航栏自定义配置可按需开启
            // .toolbarColorScheme(.dark, for: .navigationBar)
            // .toolbarBackground(Color.pacificBlue, for: .navigationBar)
            // .toolbarBackground(.visible, for: .navigationBar)
        }
        .navigationViewStyle(.stack) // 适配iPad端布局
    }
}

补充说明

  • 如果项目支持iOS15及以下版本,scrollContentBackground(.hidden)不生效也不影响功能,保留init中的UITableView全局配置即可正常运行
  • 如果不想全局配置样式影响项目其他页面,可以改用自定义Popup样式的Picker替代系统跳转式Picker,无需修改全局UI配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 08:48:00