TechnologiesSwiftUI

SecureField struct

iOSmacOStvOSwatchOSvisionOSiOS 13.0+✓ renders

A control into which people securely enter private text.

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.

  1. Bind the field to mutable state with the text parameter

    SecureField reads and writes the entered characters through a Binding<String> passed to its text: 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 password declaration, and every keystroke updates that source of truth even though the characters are never displayed.

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

  3. 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 SecureField hides it visually. The example's Text("Length: \(password.count)") reads password directly to report its character count, demonstrating that the data is fully available to your code while concealed from the screen.

  4. Style the field with text-field modifiers

    SecureField participates in the same styling system as TextField, so view modifiers like textFieldStyle(_:) apply to it. Attaching .textFieldStyle(.roundedBorder) gives the password entry a bordered appearance consistent with other text inputs in the form.

Try it — Change 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.

SecureField.swift
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()
    }
}
Live preview
Password Length: 0
Password Length: 0
swift → lexer → parser → sema → uiir → canvas Open in Studio ↗
What's new in SwiftUI 27 →