NEW: Learn SwiftUI with my free YouTube video series! >>

< 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(self.colors[$0])
            }
         }
         Text("You selected: \(colors[selectedColor])")
      }
   }
}

LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

< How to create a slider and read values from it   How to create a date picker and read values from it >
MASTER SWIFT NOW
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!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>