Best way to handle isSecureTextEntry
              
              #187
            
            
          -
| I created this  struct SecureToggle: ViewModifier {
        @State public var isSecure: Bool = true
        
        public func body(content: Content) -> some View {
            
            HStack {
                content
                    .introspectTextField { (textfield) in
                        textfield.isSecureTextEntry = isSecure
                    }
                
                Spacer()
                
                Button(action: {
                    self.isSecure.toggle()
                }) {
                    Image(systemName: isSecure ? "eye.slash":"eye")
                        .foregroundColor(Color.Nikola.lightBlue)
                }
                .padding()
            }
        }
        
    } | 
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
| It seems that SwiftUI is doing something weird behind the scenes. I don't really have a fix for you here, but as a workaround I suggest using a binding inside of  Here's some example code on how the desired behavior might be achieved: struct SecureToggle: ViewModifier {
    @Binding var isSecure: Bool
    public func body(content: Content) -> some View {
        HStack {
            content
            Spacer()
            Button(action: { self.isSecure.toggle() }) {
                Image(systemName: isSecure ? "eye.slash" : "eye")
                    .foregroundColor(Color.blue)
            }.padding()
        }
    }
}
struct ExampleView: View {
    @State private var textContent: String = ""
    @State private var isSecure: Bool = false
    
    var body: some View {
        VStack {
            Group {
                if isSecure {
                    SecureField("", text: $textContent)
                } else {
                    TextField("", text: $textContent)
                }
            }
            .modifier(SecureToggle(isSecure: $isSecure))
            .border(Color.black, width: 1)
        }.padding(20)
    }
} | 
Beta Was this translation helpful? Give feedback.
-
| Hi @moyoteg, I have also taken a look at this issue and it seems like SwiftUI changes the underlying UITextField values over and over again. That said @SplittyDev's solution is the way to go here anyway. Whenever possible, standard SwiftUI code is better than using Introspect. | 
Beta Was this translation helpful? Give feedback.
It seems that SwiftUI is doing something weird behind the scenes.
I don't really have a fix for you here, but as a workaround I suggest using a binding inside of
SecureToggleand rendering aSecureFieldinstead of a normalTextFieldwhenisSecureistrue.Here's some example code on how the desired behavior might be achieved: