Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Secure Field in SwiftUI
Written by Team Kodeco

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.
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:

  • @State private var password = "" creates a @State variable called password to bind to the view and hold the user’s input.
  • SecureField("Enter your password", text: $password) creates the secure field view, sets the placeholder text to display before the user begins entering data and binds the field to the password state variable.
  • .textContentType(.password) suggests to iOS that this is a password field, which can help with autofill and managing the user’s keychain.
  • .padding() adds some space around the view.
  • .background(RoundedRectangle(cornerRadius: 5).stroke()) gives the view a more polished appearance.
  • .multilineTextAlignment(.center) centers the view.

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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.