A TextField is a control that shows an editable text interface. In SwiftUI, a text field usually needs placeholder text and a state value that stores the user's input.
Basic Code Sample
Start with a @State variable and bind it to the text field. Adding padding helps the control avoid looking cramped.
import SwiftUI
struct ContentView: View {
@State private var textInput = ""
var body: some View {
TextField(
"Hint Text",
text: $textInput
)
.padding()
}
}Design Tip
It is often helpful to place a text field inside a stack and add a visible label. The placeholder disappears once the user types, so a persistent label keeps the form understandable after input has been entered.
HStack {
Text("First Name:")
TextField(
"Enter First Name...",
text: $textInput
)
.padding()
}Tip: placeholder text is a hint, not a label. If the field needs to remain clear after the user starts typing, include a separate Text label.
onEditingChanged
onEditingChanged is an event handler that runs when focus is given to or removed from the control.
TextField(
"Hint Text",
text: $textInput,
onEditingChanged: { changed in
// Code here
}
)
.padding()This handler fires when the user enters or leaves the field. It does not detect every keystroke, but you can compare values before and after editing if you need that behavior.
onCommit
onCommit handles the moment when the user finishes entry, such as pressing the Enter key.
TextField(
"Hint Text",
text: $textInput,
onCommit: {
// Code here
}
)
.padding()This event is commonly used to validate, clean up, or format text before processing the entered data.
Editing changed
Use this when you care about focus entering or leaving the field.
Commit
Use this when you care about the user finishing their entry.
Formatting
TextField also has overloads that accept a formatter. This lets the text field receive raw input and convert it to the appropriate formatted value.
TextField(
"Hint Text",
value: $rawInput,
formatter: NumberFormatter()
)
.padding()Notice that this initializer uses value instead of text. When the value is committed, the formatter evaluates whether the input is acceptable. If it is not valid, the field can return to the previous value or a default value.
For a number field, provide an appropriate default value, such as setting the initial value of rawInput to 0.
Styling
SwiftUI makes text field styling straightforward with textFieldStyle. The modifier accepts a style that conforms to TextFieldStyle.
TextField(
"Hint Text",
text: $textInput
)
.textFieldStyle(.roundedBorder)You can create a custom style, or use one of the built-in styles. A common ready-to-use option is a rounded border style, which gives the text field a familiar form-control appearance.
