The SwiftUI Form view gives the ability to organsise views how you need them. Forms are typilcally used on settings pages and other similar places. In this tutorial we’ll look at using a Form and how to nest a TextField, Picker, and DatePicker.
Deciding wether to use a Form or a List, for example, depends on what you need. A Form is typically used for smaller amount of organised views, like a settings page, although you can iterate within a Form and show many items. One example could be that your profile has tags with your achievements in. You could get your achievements from Swift Data, and then iterate over them in a Form.
There are no hard and fast rules on what to choose, so please do experiment to see what provides the correct look for your application.
struct ContentView: View {
@State private var name: String = ""
@State private var selectedColor = "Red"
@State private var birthDate = Date()
let colors = ["Red", "Green", "Blue", "Yellow"]
var body: some View {
NavigationStack {
Form {
Section(header: Text("Personal Info")) {
TextField("Enter your name", text: $name)
.textFieldStyle(.roundedBorder)
}
Section(header: Text("Preferences")) {
Picker("Favorite Color", selection: $selectedColor) {
ForEach(colors, id: \.self) { color in
Text(color)
}
}
.pickerStyle(.segmented)
DatePicker("Birth Date", selection: $birthDate, displayedComponents: .date)
}
Section {
Button("Save") {
print("Saved: \(name), \(selectedColor), \(birthDate)")
}
}
}
.navigationTitle("User Form")
}
}
}
We use the usual ContentView for this example which has three @State variables for storing information from the Form.
Line 6 contains an array of strings which are the names of colours. We’ll use these to iterate over in a few moments.
Next, we declare our view and nest a Form within a NavigationStack. The NavigationStack just makes things look nicer and has a title, defined on line 33.
The Form could just list a TextField, followed by a Picker, followed by a DatePicker, and then a Button. This would work just as that, but Form also allows you to break items into Sections. You can declare a Section as just a Section { with the content inbetween }, or provide it with a header: Section(header: Text(“Preferences”)) { content }
Using sections is purely a visual aspect where you can make a Form more readable by splitting it up, as you will see when you run this example.
Please reach out in the comments if you have any questions.
Leave a Reply
You must be logged in to post a comment.