Menu
Coddy logo textTech

Picker

Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 27 of 50.

A Picker chooses one value from a list of options. Each option is a view with a .tag, and the tag of the chosen option is written to the bound state:

@State private var size = "Medium"

Picker("Size", selection: $size) {
    Text("Small").tag("Small")
    Text("Medium").tag("Medium")
    Text("Large").tag("Large")
}

The tags must have the same type as the state, here String. .pickerStyle(.segmented) shows the options as a row of segments:

Picker("Size", selection: $size) {
    Text("S").tag("Small")
    Text("L").tag("Large")
}
.pickerStyle(.segmented)
challenge icon

Challenge

Easy

Add a Picker titled Milk, bound to milk, with the identifier milk and three options: Whole, Oat and Soy, each tagged with its own name. Keep the text below it, which shows the choice.

Try it yourself

import SwiftUI

@main
struct CoddyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction to SwiftUI

Practice on your own: Swift playground