WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

How to create a picker and read values from it

Paul Hudson    @twostraws   

Updated for Xcode 14.0 beta 1

SwiftUI’s Picker view manages to combine UIPickerView, UISegmentedControl, and UITableView in one, while also adapting to other styles on other operating systems. The great thing is that we really don’t have to care how it works – SwiftUI does a good job of adapting itself automatically to its environment.

As with most other controls, you must attach your picker to some sort of state that will track the picker’s selection. For example, this creates a colors array and an integer that stores which color was selected, then uses that with a picker and a text view so you can see values being read back:

struct ContentView: View {
    var colors = ["Red", "Green", "Blue", "Tartan"]
    @State private var selectedColor = "Red"

    var body: some View {
        VStack {
            Picker("Please choose a color", selection: $selectedColor) {
                ForEach(colors, id: \.self) {
                    Text($0)
                }
            }
            Text("You selected: \(selectedColor)")
        }
    }
}

Download this as an Xcode project

A wheel picker showing Red, Green, Blue, and Tartan. Blue is selected. Below is the text “You selected: Blue”.

Tip: Even though the label text isn’t visible, it’s still useful because VoiceOver will use it when reading the screen.

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.2/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.