TextField and Binding
Add text using the keyboard.
TextField and Binding
Add text using the keyboard.
0
0
Checkbox to mark video as read
Mark as read

The TextField element is used for the user to input text. When the user taps on this component, the device's keyboard automatically appears, and, as we will see in this article, we can retrieve what the user types.

Using TextField

First, we declare a variable of type String where the user's input will be stored. As an initial value, we assign it an empty String.

@State var textFieldValue: String = ""

Once the variable is declared, we can use it in our TextField.

TextField("Type here", text: $textFieldValue)
    .textFieldStyle(.roundedBorder)
    .padding()

The first element we need to indicate ("Type here"), is known as the placeholder, which is the text displayed when our TextField is empty.

The second element is the variable we created to store what the user types. As you can see, it has a $ symbol next to it. This concept is called Binding and it's explained in the next section.

Finally, with the modifier textFieldStyle() we can change the appearance of the component by drawing a rounded border around it.



Binding

This is a somewhat advanced concept that we will cover in detail later.

What you need to understand for now is that the $ symbol lets the component TextField do changes to our variable value. So, everytime the user taps a keyboard key, textFieldValue value changes automatically. This is different to other components like, for example Text(), that displays a value but it's not able to do any change on it.

To summarize this complex concept, let’s see how we use the same variable in a Text() and a TextField.

import SwiftUI

struct ContentView: View {

    @State var textFieldValue: String = ""

    var body: some View {
        VStack {
            Text("Keyboard: \(textFieldValue)")

            TextField("Type here", text: $textFieldValue)
                .textFieldStyle(.roundedBorder)
        }
        .padding()
    }
}

#Preview {
    ContentView()
}


As you can see, although the variable is the same, the Text component will only display its assigned value, so the $ symbol is not added because it won’t edit this variable, unlike the TextField component.

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy