SwiftUI TextField Tutorial

A TextField displays an editable text area. In this tutorial the entered text will be used to instantly update a text view. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUITextFieldTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView: View {
    // 1.
    @State var name: String = ""
    var body: some View {
        VStack {
            // 2.
            TextField(" Enter some text", text: $name)
                .border(Color.black)
            Text("Text entered:")
            // 3.
            Text("\(name)")
        }
        .padding()
        .font(.title)
    }
}
  1. A State property is declared which will represent the entered text inside the textfield

  2. A textfield is displayed with a placeholder text. A border modifier is added to make it clear where the boundary of the textfield is.

  3. The entered text will be diplayed inside the text view.

Go to the preview pane and select the live view button. Enter some text inside the textfield so the text view will be instantly updated.

The source code of the SwiftUITextFieldTutorial can be downloaded at the ioscreator repository on Github.