65 - Create a Form With Sections in SwiftUI

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:

SwiftUI provides Form and Section views.

Here’s what’s happening in the code:

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.