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

SwiftUI自定义Environment Value不更新问题求助

问题排查:SwiftUI自定义Environment Key值不更新的解决方法

核心错误原因

你代码里的自定义环境修饰器方法名和实际调用的方法名不匹配:

  • 你在View扩展中定义的环境传递方法是isSensitivePassword(_ value: Bool)
  • 但在Custom_EnvironmentValues里调用的却是.isSensitive(isSensitive)

名字不匹配导致环境值根本没被正确传递给PasswordField,它一直使用EnvironmentKey的默认值false,所以Toggle切换时UI完全没变化。

修复方案(二选一即可)

方案1:修正调用处的方法名

把Custom_EnvironmentValues里的调用代码改成和定义一致的方法名:

PasswordField(password: "123456")
    .isSensitivePassword(isSensitive) // 修正此处方法名

方案2:修改View扩展的方法名

保持调用代码不变,把View扩展的方法名改成你调用时用的isSensitive:

extension View {
    func isSensitive(_ value: Bool) -> some View { // 修改方法名
        environment(\.isSensitive, value)
    }
}

完整可运行代码示例

以方案1为例,完整代码如下:

struct Custom_EnvironmentValues: View {
     
     @State private var isSensitive = false

     var body: some View {
         VStack {
             Toggle(isSensitive ? "Sensitive": "Not sensitive", isOn: $isSensitive)
             PasswordField(password: "123456")
                 .isSensitivePassword(isSensitive)

         }.padding()
     }
}

struct PasswordField: View {
    
    let password: String
    @Environment(\.isSensitive) private var isSensitive
    
    var body: some View {
        HStack {
            Text("Password")
            Text(password)
                .foregroundColor(isSensitive ? .red : .green)
                .redacted(reason: isSensitive ? .placeholder: [])
            
        }
    }
}

private struct SensitiveKey: EnvironmentKey {
    static let defaultValue: Bool = false
}

extension EnvironmentValues {
    var isSensitive: Bool {
        get { self[SensitiveKey.self] }
        set { self[SensitiveKey.self] = newValue }
    }
}

extension View {
    func isSensitivePassword(_ value: Bool) -> some View {
        environment(\.isSensitive, value)
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:10:35