Picker In SwiftUI
Sep 20, 2022Pickers are control elements which let you pick a value from a list of mutually exclusive arrays. You can use it in forms or for selecting normal data.
Human Interface Guidelines Summary
Before diving into coding, let's take a look at Human Interface Guidelines summary.
- Consider this when using medium-to-long list of items.
- Use predictable and logically ordered value.
- Consider showing it as a popover or a bottom sheet rather than switching views.
Source: Apple Developer
Basic Implementation
Let's implement a normal picker using an array of strings.
@State var options = ["Swift", "Kotlin", "Java", "JavaScript"] // 1
@State var selectedItem = "Swift" // 2
var body: some View {
Picker("Pick a language", selection: $selectedItem) { // 3
ForEach(options, id: \.self) { item in // 4
Text(item) // 5
}
}
}
Result:
Code Explanation:
- Defining a state array with all the options
- Defining a state variable for saving the giving selection
- Defining a picker view - giving it a title and binding variable for selection. For the content, a for loop where we loop an array of string array is defined.
Enums with Picker
Enums go well for the integrations of picker. Let's try this out.
enum Language : String, CaseIterable { // 1
case swift
case kotlin
case java
case javascript
}
@State var selectedItem = Language.swift // 2
var body: some View {
Picker("Pick a language", selection: $selectedItem) { // 3
ForEach(Language.allCases, id: \.self) { item in // 4
Text(item.rawValue.capitalized) // 5
}
}
}
Result:
Code Explanation:
- Defining a
Language
enum of string type which is CaseIterable (it is required so that we can get all cases). - Defining a
selectedItem
variable for saving the enum case. - Defining a picker with a title and giving it a crucial variable for saving the selection.
- Looping through all cases of the enum.
- Showing Text with the capitalized raw value of the selected enum case.
Types of pickers
You can implement different types of picker using the pickerStyle()
style picker. The following styles are the styles available:
- Menu: When clicked on an item, it will show a list of items from which you can select an item on a menu type list.
- Segmented Control: This one shows the options as a radio button like action. You would have usually seen this implemented in social media profile grids.
- Wheel Picker: This provides a scrollable list of options where you can see the highlighted item at the center. You can observe this used throughout the iOS ie. clock and health app.
Note: The above types can be implemented by using.pickerStyle(...)
ie..pickerStyle(MenuPickerStyle())
. So it goes something like:Picker(...) { ... }.pickerStyle(...)
.
Congratulations! Today you learned about pickers in SwiftUI, along with picker style and learned about using enums with picker. Now that you have learned about pickers in SwiftUI, you can learn about Segmented control in SwiftUI.