Create a Picker in SwiftUI
Written by Team Kodeco
A picker is a user interface control that allows your user to pick one choice from a list of options. In SwiftUI, you can easily create a picker using the Picker
view.
Here’s an example of how to create a picker and customize its appearance:
struct ContentView: View {
let options = ["Frida Kahlo", "Georgia O'Keeffe", "Mary Cassatt", "Lee Krasner", "Helen Frankenthaler"]
@State private var selectedOption = 0
var body: some View {
VStack {
HStack {
Image(systemName: "paintpalette")
.foregroundColor(.blue)
.padding(.trailing, 4)
Text("Favorite artist:")
.font(.title)
Text(options[selectedOption])
.font(.title)
.padding(.leading, 4)
}
.padding()
Picker("Options", selection: $selectedOption) {
ForEach(options.indices, id: \.self) { index in
Text(options[index])
.font(.headline)
}
}
.pickerStyle(.wheel)
.padding()
}
}
}
Your preview should look like this:
Here’s what this code does:
- The
ContentView
struct is defined, which conforms to theView
protocol. - An array
options
is created, containing the names of different artists. - The selected option is stored in a
@State
property calledselectedOption
, with an initial value of0
. - The
body
property of the view is defined, which represents the view’s content. - Inside the
body
, aVStack
is created to vertically stack the views. - Inside the
VStack
, anHStack
is created to display the “Favorite artist” section.- An
Image
view with the system namepaintpalette
is added, adding the SF Symbol paint palette icon. - The image is styled with a blue color and given some padding.
- A
Text
view with the string “Favorite artist:” is added, representing the label. - Another
Text
view is added to display the selected artist’s name. - The text views are styled with a large font size and padding.
- An
- A
Picker
is added below the “Favorite artist” section to display the options.- The
Picker
displays a wheel-style interface for selecting options. - It uses a
ForEach
loop to iterate through theoptions
array and create aText
view for each option.
- The
- The
Picker
and “Favorite artist” section are given some padding for spacing.
Creating a picker in SwiftUI is easy and customizable. By using the Picker
view and applying different pickerStyle
modifiers, you can create a wide range of picker interfaces for your users to interact with.