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 following example shows a text field to accept a username, and a Text view below it that shadows the continuously updated value of username. The Text view changes color as the user begins and ends editing. When the user submits their completed entry to the text field, the onSubmit(of:_:) modifer calls an internal validate(name:) method.
The bound value doesn’t have to be a string. By using a FormatStyle, you can bind the text field to a nonstring type, using the format style to convert the typed text into an instance of the bound type. The following example uses a PersonNameComponents.FormatStyle to convert the name typed in the text field to a PersonNameComponents instance. A Text view below the text field shows the debug description string of this instance.
You can set an explicit prompt on the text field to guide users on what text they should provide. Each text field style determines where and when the text field uses a prompt and label. For example, a form on macOS always places the label at the leading edge of the field and uses a prompt, when available, as placeholder text within the field itself. In the same context on iOS, the text field uses either the prompt or label as placeholder text, depending on whether the initializer provided a prompt.
The following example shows a Form with two text fields, each of which provides a prompt to indicate that the field is required, and a view builder to provide a label:
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. The following example applies the roundedBorder style to both text fields within a VStack.