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