How it works
A TextField is a control that displays an editable line of text, giving people a place to enter and edit short strings such as a name, a search term, or an email address. You bind the field to a piece of your model with a Binding, and SwiftUI keeps that value in sync with what the person types, refreshing dependent views as the text changes. Reach for TextField whenever you need single-line text input; for longer, multi-line content, use TextEditor instead.
Bind the field to state with the text: parameter
The most common initializer takes a title string and a text binding. The binding is the field's source of truth: as the person edits, SwiftUI writes through it, and any change to the underlying value is reflected back in the field. Here the field is bound to
$name, the projectedBindingof the@State private var nameproperty, so the typed characters flow straight intoname.Provide a title that acts as a placeholder
The first argument is a title used both as the field's accessibility label and, when the field is empty, as gray placeholder text inside the control. It should describe the expected input rather than label a separate caption. In the example,
"Enter your name"prompts the person until they begin typing.React to edits by reading the bound value
Because the field and your state share one value, other views can observe it and update automatically as text changes. SwiftUI re-evaluates
bodyon each keystroke, so theTextview readsnameand switches between"Hello, stranger!"and an interpolated"Hello, \(name)!"live as the field's contents change.Style the field with textFieldStyle(_:)
Apply the
textFieldStyle(_:)modifier to choose how the field is drawn — its border, background, and chrome — without affecting the text-entry behavior. The example uses.roundedBorderto draw the familiar rounded rectangle around the input area;.plainand.automaticare other options.
"Enter your name" to "Search" to see how the placeholder text updates while the field's binding and behavior stay the same.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 TextFieldDemo: View {
@State private var name = ""
var body: some View {
VStack(alignment: .leading, spacing: 12) {
TextField("Enter your name", text: $name)
.textFieldStyle(.roundedBorder)
Text(name.isEmpty ? "Hello, stranger!" : "Hello, \(name)!")
.font(.headline)
}
.padding()
}
}