In this article, we will dive into SwiftUI forms and explore the usage of the TextField control. TextField is a form control that allows users to input text. It can be used to display text and enable user interaction for data entry.
Let’s start with a basic example of a TextField:
struct ContentView: View {
@State private var name = ""
var body: some View {
Form {
TextField("", text: $name)
}
}
}
In the above code snippet, we declare a TextField within a Form. The TextField takes an empty string as its first argument, which is displayed as a placeholder when the field is empty. The $name
parameter is used to bind the value entered by the user to the name
property with the help of the @State
property wrapper.
When you run the code, it will display an empty text field on the screen. You can tap on the field and enter any text:
To provide a more meaningful placeholder text, you can pass a descriptive string as the first argument of the TextField, like this:
TextField("Your name", text: $name)
This will display “Your name” as the placeholder: