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

SwiftUI中如何根据配色方案修改TextField输入文本颜色?

SwiftUI TextField输入文本颜色随深色/浅色模式切换的实现方案

当然可以实现,你的问题出在自定义的IconTextFieldStyle上——这个自定义文本字段样式接管了TextField的外观配置,导致你在TextField本身设置的foregroundStyle/foregroundColor被覆盖,所以输入文本颜色始终保持为样式里硬编码的白色。

解决步骤:

修改你的IconTextFieldStyle,让它读取环境中的colorScheme,动态适配输入文本和图标的颜色:

struct IconTextFieldStyle: TextFieldStyle {
    let iconName: String
    @Environment(\.colorScheme) private var colorScheme
    
    func _body(configuration: TextField<Self._Label>) -> some View {
        HStack {
            Image(systemName: iconName)
                .foregroundStyle(colorScheme == .light ? .black : .white)
            
            // 为输入文本设置动态颜色
            configuration
                .foregroundStyle(colorScheme == .light ? .black : .white)
        }
    }
}

为什么之前的设置无效?

SwiftUI中,TextFieldStyle的优先级高于TextField本身的外观修饰符。你在TextField上添加的foregroundStyle会被自定义样式中的配置覆盖,因此必须在样式内部处理颜色的动态切换逻辑。

调整后的PasswordResetView代码

不需要在TextField上额外设置颜色(样式已经处理),保持原有结构即可:

struct PasswordResetView: View {
    @Environment(\.colorScheme) private var colorScheme
    @Binding var showForgetPass: Bool
    @State var passwordMail: String = ""
    @ObservedObject private var authViewModel = AuthViewModel.shared
    
    var body: some View {
        VStack(spacing: 15) {
            Text("Reset Password")
                .font(.system(.title3, design: .rounded, weight: .bold))
                .foregroundStyle(colorScheme == .light ? .black : .white)
                .multilineTextAlignment(.center)
            
            TextField(text:$passwordMail) {
                Text("Email").foregroundStyle(colorScheme == .light ? .black : .white)
            }
            .textFieldStyle(IconTextFieldStyle(iconName: "envelope.fill"))
            .textInputAutocapitalization(.never)
            .keyboardType(.emailAddress)
            
            // 其他视图内容...
        }
    }
}

这样修改后,输入文本的颜色会随着系统深色/浅色模式自动切换,解决浅色模式下看不清的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 00:15:03