Mobile apps use forms to interact with users and request data. Every day when you’re using your iPhone you’ve probably been on a form. For example, the Settings app on an iPhone is a form.
As developers, these forms help us interact with the user and ask for information to complete certain operations.
In the SwiftUI framework there is a special UI component called Form. With this new control, you can easily create a form.
The Form component serves as a container to organize and group various data entry controls such as toggles or pickers.
The Form component has a single initializer with a ViewBuilder where all the elements that we want to display in the form must be included. Each view that is included in the form will correspond to a new row in the list, and we can include the Section component to create sections within the Form.
In the following code we can see how to create a form in SwiftUI with the Form component:
struct ContentView: View {
var body: some View {
Form {
// App content
}
}
}
Adding Sections to a Form
Typically the forms you create will be more complex than the simple form shown in the previous paragraph.
Using the Section view container, we can create content and group it visually. The purpose of Sections is to group content into meaningful chunks.
Sections provide visually separated content.
The code to show an example would be as follows:
struct SettingView: View {
var body: some View {
NavigationStack {
Form {
Section(header: Text("SORT PREFERENCE")) {
Text("Display Order")
}
Section(header: Text("FILTER PREFERENCE")) {
Text("Filters")
}
}
.navigationBarTitle("Settings")
}
}
}
In XCode it would give the following result: