Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add a Form in SwiftUI
Written by Team Kodeco

Forms are a great way to collect data from users in a structured manner. They offer a variety of input controls and can be easily customized to match your app’s visual style. In this cookbook entry, you’ll learn how to create a form in SwiftUI and how to add different input controls to it.

To create a simple form, you need to wrap a group of input controls within a Form view. Here’s an example:

struct ContentView: View {
  @State private var username = ""
  @State private var email = ""
  @State private var password = ""

  var body: some View {
    NavigationView {
      Form {
        Section(header: Text("Personal Information")) {
          TextField("Username", text: $username)
          TextField("Email", text: $email)
        }

        Section(header: Text("Login Credentials")) {
          SecureField("Password", text: $password)
        }

        Section {
          Button(action: register) {
            Text("Register")
          }
        }
      }
      .navigationTitle("Registration Form")
    }
  }

  func register() {
    // Implement registration functionality here
  }
}

You should see the following in the preview:

A form created in SwiftUI.
A form created in SwiftUI.

In this code example, we’ve used a Form view to create a registration form with three sections. The first section contains two text fields for the user’s username and email address. The second section contains a secure text field for the user’s password. Finally, the last section includes a button to initiate registration.

As can be seen from the code example above, the Form view provides a simple way to create different sections of input controls. You can add a header to each section by using the header parameter of the Section view. You can add a footer to each section by using the footer parameter of the Section view.

Inside each section, you can add different input controls, such as text fields, secure text fields, toggle fields, pickers and more. You can use the different input controls available in SwiftUI or implement your own custom input controls.

Finally, you can add a footer to the form by using the footer parameter of the Form view. This can be useful if you need to add additional information or instructions for your users.

For more details, see the “Forms & Controls in SwiftUI” section in this cookbook.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.