Picker is used for presenting a selection consisting of multiple options. UISegmentedControl which is known from UIKit is just a different picker style in SwiftUI. Let’s take a quick look on how to create a form with two items: picker with default style and picker with segmented style.
Creating a from
Form should be typically presented in a NavigationView which enables picker to present a list of items on a separate view in the navigation stack. Using the code below, we can create a form view which has a familiar visual style.
Setting up a picker and providing data with enum
Creating a picker requires specifying a title, a binding for selection, and function for providing a content. In the example below, we are using ForEach for creating views on demand. The number of options is defined by the number of items in the array. Each string is also used as identification of the view provided by the ForEach.
Picker with SegmentedPickerStyle
An enum which is conforming to CaseIterable protocol is a convenient way for defining data for a picker. In the example below, data is identified by enum case’s rawValue and each view has a tag equal to enum’s case. Without a tag, selection would not be displayed because there would not be a connection between the selection binding and the view returned by ForEach.
Creating a form view which uses the familiar style from iOS requires only a little bit of code in SwiftUI. Adding pickers and segmented controls, which are used a lot in forms, are pretty easy to set up.