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.
Be the first to comment