SwiftUI picker is an essential user interface 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 will explore how to create and customize pickers to fit your app’s design and functionality. We will cover various topics, including changing the appearance of pickers, creating pickers in SwiftUI Form and navigation views, using enums for data, and specific pickers such as the color picker and date picker. By the end of this tutorial, you will have a comprehensive understanding of how to use pickers in your SwiftUI projects.
Setting up a Basic SwiftUI Picker View
To start with, let’s create a basic picker view that displays a list of hardcoded data. We can do this using the Picker view in SwiftUI. I am showing static options representing food categories, such as Italian, Chinese, Indian, and American cuisine. We will bind the picker to a state variable and display the selected value.
Here’s what the code for a basic picker view looks like:
struct StaticDataPickerView: View {
@State private var selectedCategory = "Chinese"
var body: some View {
VStack {
Text("Selected Category: \(selectedCategory)")
Picker("Food Category",
selection: $selectedCategory) {
Text("Italian")
.tag("Italian")
Text("Chinese")
.tag("Chinese")
Text("Indian")
.tag("Indian")
Text("American")
.tag("American")
}
}
}
}
I also create a @State property called selectedCategory that will keep track of which item is currently selected in the picker.
Inside the body of the view, we create a Picker view with a label of “Food Category”. We bind the selectedCategory state property to the selection parameter of the picker, which means that when the user selects an item in the picker, the selectedCategory property will be updated to reflect the new selection.
Selecting Items with the Tag Modifier
In order for SwiftUI to know what selection state to set for which text view in the picker, you need to add tag modifiers. Otherwise trying to select another option will have no effect on the selection state property.
In the example above, I simply added the same tag value as shown in the text:
Text("Italian")
.tag("Italian")
Using Enums for Picker Data
Instead of using String, it is more convenient to work with enum types. In this example, we’ve defined an enum called FoodCategory that conforms to the CaseIterable and Identifiable protocols. The CaseIterable protocol allows us to iterate over all the cases of the enum, which will be useful when we create the picker. The Identifiable protocol allows us to use the enum as the identifier for the picker’s selections.
enum FoodCategory: String, CaseIterable, Identifiable {
case italian = "Italian"
case mexican = "Mexican"
case chinese = "Chinese"
case indian = "Indian"
case american = "American"
var id: FoodCategory { self }
}
Each case of the enum represents a different food category, and we’ve assigned a string value to each case that will be used as the label for the picker’s selections. We’ve also defined a computed property called id that returns the enum itself, which allows us to use the enum as the identifier for the picker’s selections.
Here’s an example of how we could use this enum to create a picker:
struct FoodPicker: View {
@State private var selectedCategory: FoodCategory = .italian
var body: some View {
Picker("Food Category", selection: $selectedCategory) {
ForEach(FoodCategory.allCases) { category in
Text(category.rawValue).tag(category)
}
}
}
}
In this example, we’ve created a FoodPicker view that contains a picker for selecting a food category. We’ve defined a state variable called selectedCategory that will hold the currently selected category.
In the body of the view, we’ve created a Picker with a label of “Food Category” and a selection binding to the selectedCategory state variable. We’ve used a ForEach loop to iterate over all the cases of the FoodCategory enum and create a Text view for each one with the label text set to the raw value of the enum case. We’ve also used the tag modifier to associate each Text view with its corresponding enum case.
When the user selects a category from the picker, the selectedCategory state variable will be updated with the corresponding enum case.
Customizing the Appearance of the Picker Style
SwiftUI offers several built-in picker styles to change the appearance and behavior of your pickers. The main picker styles are:
- 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.
By default, pickers use the DefaultPickerStyle, which is menu style. You can change this by adding the listStyle modifier like so:
Picker(
...
).pickerStyle(.segmented)
Specific pickers: SwiftUI color picker, date picker, multi date picker
In this section, we will focus on specific types of pickers, including color picker, date picker, and multi-date picker. These pickers offer specialized functionality for selecting colors, single dates, or multiple dates, which can be useful in various app scenarios.
SwiftUI ColorPicker
To add a color picker to your app, first, create a state variable that will store the selected color. Next, add the ColorPicker view to your app’s body. The color picker is now bound to the selectedColor state variable using the $ symbol. SwiftUI will automatically update the state when the user selects a different color.
To use the selected color in your app, simply apply it to other views. For example, you can change the background or foreground color of a Text view based on the selected color.
import SwiftUI
struct ColorPickerExampleView: View {
@State private var selectedColor: Color = Color.red
var body: some View {
VStack(spacing: 20) {
ColorPicker("Select a Color",
selection: $selectedColor)
Text("Your selected color is used here")
.foregroundColor(selectedColor)
}
.padding()
}
}
On iOS the color options are shown in a sheet.
With this setup, the Text view’s foreground color will change as the user selects different colors from the color picker. The same approach can be applied to other views that support color customization.
Selecting Date values with the SwiftUI DatePicker
Let’s explore the Date Picker and Multi-Date Picker components in SwiftUI and provide examples for each. To add a date picker to your app, start by creating a state variable that will store the selected date.
Next, add the DatePicker view to your app’s body. The DatePicker is now bound to the selectedDate state variable using the $ symbol. SwiftUI will automatically update the state when the user selects a different date.
To display the selected date, you can use a Text view and format the date using a DateFormatter, which you can see in action in this post Swift Date Formatting: 10 Steps Guide.
struct ContentView: View {
@State private var selectedDate: Date = Date()
private let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
var body: some View {
VStack(spacing: 30) {
DatePicker("Select a Date",
selection: $selectedDate,
displayedComponents: .date)
Text("Selected Date: \(selectedDate, formatter: dateFormatter)")
}
.padding()
}
}
With iOS 16 you can now allow the user to select multiple dates:
struct ContentView: View {
@State private var dates: Set<DateComponents> = []
var body: some View {
MultiDatePicker("Select Time Frame", selection: $dates)
}
}
Comparing Picker with other SwiftUI Control Views like Toggle, Stepper, Menu, and Button
In this section, I will compare and contrast different control views in SwiftUI including pickers, toggles, buttons, and menus. You can see how they look like in the below image:
struct ContentView: View {
@State private var selectedCategory: FoodCategory = .italian
@State private var isOn = true
@State private var number: Double = 10
@State private var rating: Double = 10
var body: some View {
VStack(spacing: 40){
Menu("Menu") {
Button("Action 1") { }
Button("Action 2") { }
}
.menuStyle(.borderlessButton)
Button("Do something") {
}
.buttonStyle(.plain)
Picker("Food Category", selection: $selectedCategory) {
ForEach(FoodCategory.allCases) { category in
Text(category.rawValue)
}
}
.pickerStyle(.segmented)
Toggle("Is \(isOn ? "On" : "Off")", isOn: $isOn)
Stepper("Selected number: \(Int(number))",
value: $number,
in: 0...100,
step: 1)
Text("Your selected rating: \(Int(rating)) ")
Slider(value: $rating, in: 0...100, step: 10)
}
}
}
Control View | Style | |
---|---|---|
Button | Buttons are a fundamental UI element that can trigger actions when tapped. | .bordered, .borderless, .borderedProminent, .plain |
Picker | Designed to present multiple options for users to select from. They are ideal when you have a predefined set of options and want to allow users to select one. | .wheel, .inline, .segmented, .menu, .radioGroup |
DatePicker and MultiDatePicker | Specific picker to select one or more dates. | .compact, .wheel, .graphical |
Toggle | Toggles are UI elements that allow users to switch between two states, typically on and off. They are suitable when you need to represent a boolean value or enable/disable a specific feature. | .switch, .botton, .checkbox |
Stepper | Stepper is a UI element that provides an intuitive way for users to adjust numeric values within a specified range. It allows users to increment or decrement the value by tapping on plus (+) or minus (-) buttons. | no styling options |
Menu | Menus are a UI element that presents a list of options when tapped. They are suitable when you have limited screen space or want to provide multiple actions without cluttering the UI. | .borderlessButton, .button |
Conclusion
In conclusion, pickers are a powerful tool for collecting user input in your SwiftUI apps. By providing a selection binding, a label, and the content for the picker to display, you can create a variety of different pickers to suit your needs.
Pickers are particularly useful when you need to collect input from a set of mutually exclusive values. For example, you might use a picker to allow users to select a color, a date, or a food category, as we’ve seen in this tutorial.
Overall, pickers are a versatile and intuitive way to collect user input in your SwiftUI apps. By using the techniques and examples covered in this tutorial, you can create pickers that are tailored to match your specific needs and enhance the user experience of your app.
FAQ
How do I open a color picker in SwiftUI?
You can open a solor picker by tapping on the color indicator. This will open a sheet for iOS and a popover on macOS and iPad.
What is the default picker style in SwiftUI?
The default picker style in SwiftUI depends on the platform and context in which the picker is used. For example, on iOS, the default picker style is a wheel that allows users to scroll through the available options.
How do I make a horizontal picker in SwiftUI?
You can make a horizontal picker in SwiftUI by using the Picker view and setting its PickerStyle to SegmentedPickerStyle. This will create a picker with horizontal segments that the user can tap to select an option.
How do I use a picker in Swift?
You can use a picker in Swift by creating a Picker view and providing a selection binding, a label, and the content for the picker to display. You can customize the appearance and behavior of the picker using different styles and modifiers.
How do I show a date picker in Swift?
You can show a date picker in SwiftUI by using the DatePicker view. This view allows users to select a date and/or time from a calendar or clock interface and provides a binding to the selected date.
What is a number picker in Swift?
A number picker in Swift is a type of picker view that allows users to select a number from a range of values. This type of picker is commonly used in apps that require numerical input, such as fitness and finance apps.
How do I make a number picker in SwiftUI?
You can make a number picker in SwiftUI by using the Stepper view. This view allows users to increment or decrement a value by a specified amount and provides a binding to the selected value. You can customize the appearance and behavior of the stepper using different styles and modifiers.
Further Reading
- Find examples of picker used with SwiftUI Form
- Learn more about enums in this blog post “Understanding Swift Enumeration: Enum with Raw Value and Associated Values”
- How to create a drop-down picker with Menu
- Format date types in this post Swift Date Formatting: 10 Steps Guide.