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

如何设置SwiftUI Picker的字体颜色?解决字体始终为蓝色问题

SwiftUI Picker 字体颜色设置问题

我有一个SwiftUI Picker,选中high、medium或low选项时,Picker的轮廓会变为对应颜色。现在我希望将Picker背景设置为对应颜色(已实现该操作),同时将字体颜色设置为白色,但字体始终显示为蓝色。请问是否可以通过内置Picker设置字体颜色?

原始代码

import SwiftUI

struct ContentView: View {
    @State private var gaugeLevel: GaugeLevel = .low

    var body: some View {

        ZStack {
            
            RoundedRectangle(cornerRadius: 20)
                .fill(Color.white) 
                .overlay(
                    RoundedRectangle(cornerRadius: 20)
                        .stroke(gaugeLevel.color, lineWidth: 2)
                )
                .frame(width: 120, height: 25)
            
            Picker("Level", selection: $gaugeLevel) {
                ForEach(GaugeLevel.allCases, id: \.self) { level in
                    Text(level.rawValue.capitalized).tag(level)
                }
            }
        }
    }
}

enum GaugeLevel: String, CaseIterable, Identifiable {
    case high, medium, low

    var color: Color {
        
        switch self {
        case .high:
            return .red
            
        case .medium:
            return .orange
            
        case .low:
            return .green
        }
    }
    var id: Self {self}
}

#Preview {
    ContentView()
}

已采纳的解决方案代码

Picker("Level", selection: $gaugeLevel) {
    ForEach(GaugeLevel.allCases, id: \.self) { level in
        Text(level.rawValue.capitalized).tag(level)
            
    }
}
.background(gaugeLevel.color)
.accentColor(Color.white)
.cornerRadius(20)

解决方案说明

SwiftUI的Picker默认使用系统强调色作为选中项的文本颜色,通过添加.accentColor(Color.white)修饰符,即可将Picker的选中文本颜色改为白色,配合.background(gaugeLevel.color)设置的对应背景色,就能实现需求中的视觉效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 19:20:28