How it works
A SecureField is a control that lets people enter private text, such as a password, while obscuring the characters as they type. It behaves like a TextField but masks its contents on screen and signals to the system that the input is sensitive, so the platform can disable features like autocorrect, copy, and screen capture of the value. Reach for SecureField whenever you collect a secret the user wouldn't want shown in plain text or exposed to onlookers.
Bind the field to mutable state with the text parameter
SecureFieldreads and writes the entered characters through aBinding<String>passed to itstext:parameter, so it needs a two-way connection to your model. In the example the field binds to$password, the projected value of the@State private var passworddeclaration, and every keystroke updates that source of truth even though the characters are never displayed.Supply a prompt with the title parameter
The first argument is a title string that acts as the field's label and placeholder, describing what to enter when the field is empty. Here
SecureField("Password", text: $password)shows "Password" as guidance until the user begins typing, at which point the entry is replaced by masking dots.Read the bound value like any other String
Because the binding stores ordinary text, the rest of your view can observe and use it even though
SecureFieldhides it visually. The example'sText("Length: \(password.count)")readspassworddirectly to report its character count, demonstrating that the data is fully available to your code while concealed from the screen.Style the field with text-field modifiers
SecureFieldparticipates in the same styling system asTextField, so view modifiers liketextFieldStyle(_:)apply to it. Attaching.textFieldStyle(.roundedBorder)gives the password entry a bordered appearance consistent with other text inputs in the form.
SecureField to TextField in SecureField("Password", text: $password) and type the same text to watch the characters appear in plain text instead of being masked.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct SecureFieldDemo: View {
@State private var password = ""
var body: some View {
VStack(alignment: .leading, spacing: 12) {
SecureField("Password", text: $password)
.textFieldStyle(.roundedBorder)
Text("Length: \(password.count)")
.font(.caption)
.foregroundStyle(.secondary)
}
.padding()
}
}