/

SwiftUI Forms: Exploring TextField

SwiftUI Forms: Exploring TextField

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:

1
2
3
4
5
6
7
8
9
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:

Empty TextField

TextField with Text

To provide a more meaningful placeholder text, you can pass a descriptive string as the first argument of the TextField, like this:

1
TextField("Your name", text: $name)

This will display “Your name” as the placeholder:

TextField with Placeholder

tags: [“SwiftUI”, “forms”, “TextField”, “user input”, “@State”]