Home > Blockchain >  SwiftUI Custom Environment Value
SwiftUI Custom Environment Value

Time:11-11

I try to make custom environment key to read its value as shown in the code below, I read many resources about how to make it and all have the same approach. Example Code

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

     var body: some View {
         VStack {
             // Update the value here <---
             Toggle(isSensitive ? "Sensitive": "Not sensitive", isOn: $isSensitive)
             PasswordField(password: "123456")
                 .isSensitive(isSensitive)

         }.padding()
     }
}

struct PasswordField: View {
    
    let password: String
    @Environment(\.isSensitive) private var isSensitive
    
    var body: some View {
        HStack {
            Text("Password")
            Text(password)
                 // It should update the UI here but that not happened <---
                .foregroundColor(isSensitive ? .red : .green)
                .redacted(reason: isSensitive ? .placeholder: [])
            
        }
    }
}

// 1
private struct SensitiveKey: EnvironmentKey {
    static let defaultValue: Bool = false
}
// 2
extension EnvironmentValues {
    var isSensitive: Bool {
        get { self[SensitiveKey.self] }
        set { self[SensitiveKey.self] = newValue }
    }
}
// 3
extension View {
    func isSensitivePassword(_ value: Bool) -> some View {
        environment(\.isSensitive, value)
    }
}

When I try to make a custom environment value and read it, its not work, the key value not update at all.

CodePudding user response:

Your function is returning the environment, not the modified view. Try this:

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

CodePudding user response:

You just need to inject into the environment

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

     var body: some View {
         VStack {
             Toggle(isSensitive ? "Sensitive": "Not sensitive", isOn: $isSensitive)
                 
             PasswordField(password: "123456")
             //HERE <<---
             .environment(\.isSensitive, isSensitive)
             //or
             //.isSensitivePassword(isSensitive) //your function name
         }.padding()

     }
}
  • Related