123 - Create a Text Field in SwiftUI

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.

In this example:

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.