Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Hide User Input Using a SecureField in SwiftUI
Written by Team Kodeco

Protecting user’s sensitive information is a fundamental principle in app development. This is especially true when you’re dealing with inputs such as passwords, PINs or any other form of personal identifiable information (PII). This is where secure text entry becomes an essential part of your user interface. SwiftUI provides an intuitive and straightforward way to implement this secure text entry via the SecureField view.

SecureField ensures that the user’s input is hidden from view as they type, making it an ideal component for any form that requires the user to enter confidential or sensitive information. This not only preserves privacy but also helps in preventing shoulder surfing attacks, where an attacker tries to capture the user’s credentials by looking over the user’s shoulder.

Here’s an example of how you can add secure text entry to a text field in SwiftUI:

struct ContentView: View {
  @State private var password = ""

  var body: some View {
    SecureField("Password", text: $password)
      .textFieldStyle(.roundedBorder)
      .padding()
      .cornerRadius(10)
      .shadow(radius: 10)
      .padding()
      .frame(width: 300)
      .padding(.bottom, 50)
  }
}

Here’s what your preview will look like after entering some text:

A text field with secure text entry in SwiftUI.
A text field with secure text entry in SwiftUI.

In the above code, you use the SecureField view to create a password input field. As the user types, their input is immediately obscured, providing a secure text entry experience. Using the $password binding, we can keep track of the text input securely without exposing it visually.

In summary, SecureField is a vital tool in SwiftUI that enables you to create secure text fields quickly and effectively. It’s an essential component for maintaining user trust and privacy within your application.

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.