Picker and segmented control in SwiftUI on iOS

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.

Form view in navigation view for enabling navigation stack.
Example app presenting a form with pickers.

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.

Creating a picker with a list of items.

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.

Picker displayed with segmented control style.

Summary

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s