How to create and use Picker with Form in SwiftUI

Picker is a control in SwiftUI which allows you to select a value from a list of possible options. In order to properly use a Picker, you need to back it with an array of possible options to choose from and a State variable storing the index of selected option in the array.

In its simplest form, a Picker can be used like this:

struct ContentView: View {
   var frameworks = ["UIKit", "Core Data", "CloudKit", "SwiftUI"]
   @State private var selectedFrameworkIndex = 0

   var body: some View {
      VStack {
        Picker(selection: $selectedFrameworkIndex, label: Text("")) {
            ForEach(0 ..< frameworks.count) {
               Text(self.frameworks[$0])
            }
         }
         Text("Your favorite framework: \(frameworks[selectedFrameworkIndex])")
      }.padding()
   }
}

The result is presented below. It’s functional and works as expected but to be honest it doesn’t look great because it takes up a large chunk of screen. In the next section we’re going to fix it by placing the Picker in a Form.

SwiftUI Picker
SwiftUI Picker

Using Picker in a Form

A Form in SwiftUI is a container view which allows you to group controls used for data entry. By wrapping the Picker in a From, we’re giving it extra functionality – the picker now becomes a single horizontal row with selected value in it. Tapping on the picker navigates away to a new view which contains a list of possible options. Tapping a desired option, selects it and navigates back to the original view.

Note that in order to allow for this functionality to happen, your top level view containing the picker has to be a NavigationView.

Let’s take a look at the code. Update the body of your ContentView to reflect the new functionality:

var body: some View {
    NavigationView {
        Form {
            Section {
                Picker(selection: $selectedFrameworkIndex, label: Text("Favorite Framework")) {
                    ForEach(0 ..< frameworks.count) {
                        Text(self.frameworks[$0])
                    }
                }
            }
        }
        .navigationBarTitle("Favorites")
    }
}

The result looks like this:

Picker in a Form - SwiftUI
Picker in a Form – SwiftUI

Check out Apple’s official documentation of Picker and Form.

Related tutorials: