Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show/Hide Password - How can I add this feature?

Tags:

swift

swiftui

I've looked through the forums but I'm seeing mixed answers especially ones from an old Xcode version.

I only decided to add this after already typing up the code I have in this: Photo

How could I go about doing that? I was wanting the 'Eyeball' toggle implemented on the password field.

like image 684
Moe Kurdi Avatar asked Jul 26 '20 03:07

Moe Kurdi


1 Answers

enter image description hereYou can simply use this view instead of SecureField. It has the eye icon inside, so for most cases you don't need to care about anything.

struct SecureInputView: View {
    
    @Binding private var text: String
    @State private var isSecured: Bool = true
    private var title: String
    
    init(_ title: String, text: Binding<String>) {
        self.title = title
        self._text = text
    }
    
    var body: some View {
        ZStack(alignment: .trailing) {
            Group {
                if isSecured {
                    SecureField(title, text: $text)
                } else {
                    TextField(title, text: $text)
                }
            }.padding(.trailing, 32)

            Button(action: {
                isSecured.toggle()
            }) {
                Image(systemName: self.isSecured ? "eye.slash" : "eye")
                    .accentColor(.gray)
            }
        }
    }
}

Copy paste this view into your app, and instead of SecureField just use SecureInputView.

Example: SecureInputView("Password", text: $viewModel.password)

like image 115
Vahagn Gevorgyan Avatar answered Oct 21 '22 19:10

Vahagn Gevorgyan