A picker is an essential UI component used to collect data from users. With a picker, users can choose from a set of predefined values and make a selection with ease. In this tutorial, we’ll explore how to create and customize pickers to fit your app’s design and functionality.
Setting up a Basic SwiftUI Picker View
To start, we’ll create a basic picker that displays a list of data. Our user will be able to select which language they want to learn. To handle this input, we’ll use a picker. We’ll start by declaring an array called languages as follows:
private var languages = ["English", "Spanish", "Italian", "French", "Portuguese"]
To use a picker, we also need to declare the state variable to store the user’s selection. So, we’ll declare the following variable:
@State private var selectedLanguage = 0
Here 0 means the first item in the languages array. The code to display the picker would be the following:
Picker(selection: $selectedLanguage, label: Text("Language To Learn")) {
ForEach(0..<languages.count, id: \.self) {
Text(self.languages[$0])
}
}
Which in XCode would result in:
This is how you can create a picker in SwiftUI. You need to provide two values: the selection binding ($selectedLanguage) and the text label describing each option. Inside the closure, the available options are displayed with text views.
Customizing the Appearance of the Picker
SwiftUI offers quite a few built-in styles to change the appearance and behavior of a picker. The main styles are as follows:
DefaultPickerStyle: Automatically adapts to the platform and environment.
WheelPickerStyle: Displays a spinning wheel picker
SegmentedPickerStyle: Presents the options as a segmented control.
InlinePickerStyle: Displays the options in a list or table, inline with the content.
MenuPickerStyle: Presents the options in a menu when tapped.
For example, if we use the .wheel style as follows
Picker(
…
)
.pickerStyle(.wheel)
we will see the picker like this in XCode:
1 comment