Create a Form With Sections in SwiftUI
Written by Team Kodeco
Forms are an essential part of any application that requires user input. By dividing your form into multiple sections, you can better group related fields together and make it easier for users to enter their information.
Here’s an example:
struct ContentView: View {
@State private var name = ""
@State private var email = ""
@State private var age = ""
var body: some View {
NavigationStack {
Form {
Section(header: Text("Personal Information")) {
TextField("Name", text: $name)
TextField("Email", text: $email)
}
Section(header: Text("Additional Information")) {
TextField("Age", text: $age)
}
}
.navigationTitle("Registration Form")
}
}
}
Your preview should look like this:
Here’s what’s happening in the code:
-
The
NavigationStack
is a container that provides a platform-adaptive structure for navigation. Your form will display inside thisNavigationStack
. -
Form
is a SwiftUI container view that you use to gather information from the user. It consists of different types of views such as text fields, buttons and toggles. In this example, the form contains twoSection
views. -
Section
is a SwiftUI container that you use to group related content. A section can have a header, a footer and content. Here, you see two sections: “Personal Information” and “Additional Information”, each with twoTextField
views. -
TextField
creates an editable text interface. The first parameter of theTextField
is the placeholder, and the second parameter is a binding to a state variable where the user’s text will be stored. The $ denotes a binding in SwiftUI, meaning a two-way connection between theTextField
and its bound variable. Whenever the bound variable changes, SwiftUI will redraw the text field. -
The
@State
keyword is a property wrapper provided by SwiftUI. It’s a way to declare a source of truth for data in your app that can be mutated. SwiftUI will automatically update the UI when the data changes. -
The
.navigationTitle("Registration Form")
modifier is used to set the title of the navigation bar.
Remember, the goal is to make it easier for users to input their information by organizing your form into logical sections. SwiftUI’s composability makes this task straightforward and intuitive. Keep experimenting, and you’ll master SwiftUI forms in no time.