Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Text Field in SwiftUI
Written by Team Kodeco

Text fields are the bread and butter of user input in SwiftUI. They are defined using the TextField view, which can be styled and customized extensively.

To get a text field up and running, you first need a @State variable for it to bind to. Here’s how it works in practice:

struct ContentView: View {
  @State private var textFieldInput = ""

  var body: some View {
    VStack {
      TextField("Enter text here", text: $textFieldInput)
        .textFieldStyle(.roundedBorder)
        .padding()
        .font(.headline)
      
      Text("You entered: \(textFieldInput)")
    }
  }
}

Enter some text in the text field and your preview will look something like this:

A text field in SwiftUI.
A text field in SwiftUI.

In this example:

  • “Enter text here” is the placeholder, giving users an indication of what they should type in.
  • textFieldInput is a @State variable that holds the user’s text input. By using the $ symbol, you bind this variable to the text field, meaning SwiftUI will keep it updated as the text field’s content changes.
  • The .textFieldStyle(.roundedBorder) modifier gives your text field a pleasing aesthetic with rounded corners.
  • With the .padding() and .font(.headline) modifiers, you create a comfortable space around the text field and adjust its font size, respectively.

The live data flow between the text field and the Text view beneath it is demonstrated as the output from the text field is displayed in real time.

Armed with these fundamental skills, you’re now ready to incorporate your own text fields in SwiftUI and unlock the potential of user input.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.