How to Update Text Using a TextField in SwiftUI

TextField.png

Being able to enter text into an app is essential. In this short tutorial you’ll learn how to create a TextField, bind it to a value, and update its style so you can give your users a way to enter text in your apps.

Setting up

To get set up we’ll need a few things: A state property to bind our TextField to, a VStack, and a Text view to display the text the user enters.

@State private var displayText: String = "Enter some text"

var body: some View {
    VStack {
        Text(displayText)
            .font(.title)
    }
    .padding()
}

I went ahead and set the Text’s font to title and added some padding, but feel free to set things up however you’d like!

Adding a TextField

Now that we have a state property (displayText) and a way to display the user’s text input it’s time to add a TextField.

TextField("Display Text Field", text: $displayText)

As with most controls in SwiftUI, TextField takes a string for its title. While this title isn’t displayed by default, it’s important to add a descriptive title to improve accessibility in your app.

OK great, so now we’ve got a TextField that has a binding to the property we’re using to store the text. But it doesn’t really look like a normal text field just yet. Instead, you should see what looks like a left-aligned label. To fix that all you need to do is set a style for your TextField with the .textFieldStyle modifier.

TextField("Display Text Field", text: $displayText)
    .textFieldStyle(RoundedBorderTextFieldStyle())

Now you should see a rounded border around your text field! You can find a list of all of the available text field styles in Apple’s documentation here.

Check out some other recent tutorials

Previous
Previous

How to Set the Background Color in SwiftUI

Next
Next

Using dropLast and removeLast in Swift