How to read Password from User in SwiftUI?

SwiftUI SecureField – Read Password from User

To read password from user in SwiftUI, use SecureField. SecureField is like TextField, except that the characters are displayed as dots not revealing the actual data in the UI.

Example

In the following example, we will define a SecureField and read password from user.

Define a state variable password to store the password entered by user in the SecureField. Bind this variable password for text field in SecureField.

ContentView.swift

import SwiftUI

struct ContentView: View {
    @State private var password: String = ""
    
    var body: some View {
        SecureField(
            "Password",
            text: $password
        ) {
            //on commit code
        }
        .padding(.all)
        .textFieldStyle(RoundedBorderTextFieldStyle())
    }
}

Screenshot

SwiftUI SecureField - Read Password from User

When user starts entering password, the password is displayed as dots as shown in the following screenshot.

SwiftUI SecureField - Read Password from User

Summary

Summarising this SwiftUI Tutorial, we learned how to setup SecureField control to read password from user.