Create a Text Field in SwiftUI
Written by Team Kodeco
The TextField
in SwiftUI is a versatile element used to capture text input from the user. You create a TextField
by providing a placeholder string, which displays when the field is empty and a binding to a variable where the text input will be stored.
Here’s a simple example:
struct ContentView: View {
@State private var name = ""
var body: some View {
TextField("Enter your name", text: $name)
.multilineTextAlignment(.center)
}
}
In this example, "Enter your name"
serves as the placeholder text, and text: $name
creates a two-way binding to the name
state variable. This means that any text inputted by the user into the text field will be stored in the name
variable. The multilineTextAlignment
modifier is used to center the text within the TextField
.
Customizing the Appearance of a Text Field
Styling the TextField
can greatly enhance the user experience. SwiftUI provides various view modifiers for customization, including font, foreground color and background color.
Here’s an example that adjusts these properties:
struct ContentView: View {
@State private var name = ""
var body: some View {
TextField("Enter your name", text: $name)
.foregroundColor(.blue)
.background(.yellow)
.font(.largeTitle)
.multilineTextAlignment(.center)
}
}
In this snippet, .font(.largeTitle)
modifies the font of the text to be the large title style. .foregroundColor(.blue)
changes the text color to blue and .background(.yellow)
sets the background color of the TextField
to yellow.
Here’s what this looks like with a name entered:
Enhancing TextField Interaction
Beyond appearance, the behavior and interaction of a TextField
can be modified. For instance, you can disable autocorrection or apply automatic capitalization styles depending on the context of the input.
You can also respond to certain user actions, like when they submit the form, by using the onSubmit
modifier. This triggers a provided closure when the user triggers the default action, such as pressing return on the keyboard.
For more on TextField
, see the “Text Input in SwiftUI” section in this cookbook.