32 - Create a Secure Field in SwiftUI

When building forms in SwiftUI, you may need to collect sensitive information from users, such as a password or PIN. To create a secure text field that hides this input from prying eyes, you can use the SecureField view.

To create a secure field with a placeholder, you can simply pass the placeholder text as a parameter:

struct ContentView: View {
  @State private var password = ""
  var body: some View {
    SecureField("Enter your password", text: $password)
      .textContentType(.password)
      .padding()
      .background(RoundedRectangle(cornerRadius: 5).stroke())
      .multilineTextAlignment(.center)
  }
}

The preview should look as follows:

Use SwiftUI's SecureField view to gather sensitive information.

In this example, $password represents a @State variable that holds the user’s input.

Here’s what’s happening in the code above:

By using SecureField for password inputs, you can ensure that sensitive information remains hidden from view, while still providing a familiar and easy-to-use input experience for users.