Structure¶
TextField¶
A view for editable text.¶
Declaration¶
struct TextField<Label> : View where Label : View
Overview¶
TextField provides an interface to display and modify editable text.
You create a text field with a label and a binding to a value. If the value is a string, the text field updates this value continuously as the user types or otherwise edits the text in the field. For non-string types, it updates the value when the user commits their edits, such as by pressing the Return key.
The text field also allows you to provide two closures that customize its behavior. The onEditingChanged property informs your app when the user begins or ends editing the text. The onCommit property executes when the user commits their edits.
TextField has 4 different initializers, and is most commonly initialized with a @State variable and placeholder text.
struct ExampleView: View {
@State var myFruit: String = ""
var body: some View {
VStack {
Text(myFruit)
TextField("Fruit", text: $myFruit)
}
.padding()
}
}

Styling Text Fields¶
SwiftUI provides a default text field style that reflects an appearance and behavior appropriate to the platform. The default style also takes the current context into consideration, like whether the text field is in a container that presents text fields with a special style. Beyond this, you can customize the appearance and interaction of text fields using the textFieldStyle(_:) modifier, passing in an instance of TextFieldStyle.
TextField can be styled with the textFieldStyle(_:) modifier.
struct ExampleView: View {
@State var myFruit: String = ""
var body: some View {
Text(myFruit)
TextField("Fruit", text: $myFruit)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
}
}

The TextFieldStyle protocol and textFieldStyle(_:) modifier provide helpful functionality to implement a well styled TextField.
Availability¶
iOS 13.0+
macOS 10.15+
tvOS 13.0+
watchOS 6.0+
Topics¶
Initializer¶
init(_:text:onEditingChanged:onCommit:) Creates a text field with a text label generated from a localized title string.
init(_:text:onEditingChanged:onCommit:) Creates a text field with a text label generated from a title string.
init(_:value:formatter:onEditingChanged:onCommit:) Create an instance which binds over an arbitrary type, T.
init(_:value:formatter:onEditingChanged:onCommit:) Create an instance which binds over an arbitrary type, T.
Instance Property¶
body The content and behavior of the view.
Type Alias¶
Body The type of view representing the body of this view.