NEW: Get your ticket for Hacking with Swift Live 2019! >>

< How to create a Slider and read values from it   How to create a date picker and read values from it >

How to create a picker and read values from it

SwiftUI’s Picker view manages to combine UIPicker 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 = 0

   var body: some View {
      VStack {
         Picker(selection: $selectedColor, label: Text("Please choose a color")) {
            ForEach(0 ..< colors.count) {
         Text("You selected: \(colors[selectedColor])")

Note: It’s important that you place your picker view inside something to ensure it appears in the default wheel style on iOS.

HACKING WITH SWIFT LIVE This July is a new two-day event where you'll be inspired by great speakers on day one then learn all the amazing new features from WWDC on day two – click here for more information and tickets.

< How to create a Slider and read values from it   How to create a date picker and read values from it >
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>