SwiftUI Picker

Pickers are a fundamental UI component that allow users to select from a list of options. In SwiftUI, the `Picker` view provides a flexible and powerful way to create drop-down menus, selection wheels, and other types of selectors

article

Pickers are a fundamental UI component that allow users to select from a list of options. In SwiftUI, the `Picker` view provides a flexible and powerful way to create drop-down menus, selection wheels, and other types of selectors. This article will guide you through the basics of creating and customizing pickers, handling picker selections, and integrating pickers into forms and other interfaces.


Creating a Simple Picker


At its core, a `Picker` in SwiftUI is used to allow the user to select one or more options from a set of choices. You need to bind the picker to a state variable that tracks the selected value. Here’s a basic example of creating a picker:



struct ContentView: View {
    @State private var selectedColor = "Red"
    let colors = ["Red", "Green", "Blue"]
    
    var body: some View {
        Picker("Select a color", selection: $selectedColor) {
            ForEach(colors, id: \.self) {
                Text($0)
            }
        }
        .padding()
        .pickerStyle(SegmentedPickerStyle())
    }
}

In this example, the picker allows the user to select a color from the options "Red," "Green," and "Blue." The `Picker` is bound to the `selectedColor` state variable, which updates automatically when the user selects a different option. The picker style is set to `SegmentedPickerStyle`, displaying the options as a segmented control.


Picker Styles in SwiftUI


SwiftUI provides several built-in picker styles that determine how the picker is presented. Each style offers a different user experience and is suited to different types of applications. Here are a few commonly used picker styles:


SegmentedPickerStyle


The `SegmentedPickerStyle` displays options as a horizontal set of segments. This style is ideal for cases where you have a small number of options, and you want the user to see all the choices at once:



Picker("Select a color", selection: $selectedColor) {
    ForEach(colors, id: \.self) {
        Text($0)
    }
}
.pickerStyle(SegmentedPickerStyle())

WheelPickerStyle


The `WheelPickerStyle` displays options as a scrolling wheel, similar to the date and time pickers found in many iOS apps. This style is useful for selecting from a larger set of options:



Picker("Select a color", selection: $selectedColor) {
    ForEach(colors, id: \.self) {
        Text($0)
    }
}
.pickerStyle(WheelPickerStyle())

MenuPickerStyle


The `MenuPickerStyle` presents the options in a drop-down menu. This style is ideal for compact UI designs where space is limited:



Picker("Select a color", selection: $selectedColor) {
    ForEach(colors, id: \.self) {
        Text($0)
    }
}
.pickerStyle(MenuPickerStyle())

Handling Picker Selections


When a user selects an option from a picker, SwiftUI automatically updates the bound state variable. You can also perform additional actions in response to the selection change using the `.onChange()` modifier:



Picker("Select a color", selection: $selectedColor) {
    ForEach(colors, id: \.self) {
        Text($0)
    }
}
.onChange(of: selectedColor) { newValue in
    print("Selected color: \(newValue)")
}
.pickerStyle(WheelPickerStyle())

In this example, whenever the user selects a new color, the new value is printed to the console. This approach is useful for triggering additional logic or UI updates based on the user’s selection.


Integrating Pickers into Forms


Pickers are often used in forms where users need to select options from predefined choices. SwiftUI makes it easy to integrate pickers into forms using the `Form` view, which automatically organizes the layout for input fields. Here’s an example of a picker in a form:



struct SettingsView: View {
    @State private var selectedOption = "Option 1"
    let options = ["Option 1", "Option 2", "Option 3"]
    
    var body: some View {
        Form {
            Section(header: Text("Preferences")) {
                Picker("Choose an option", selection: $selectedOption) {
                    ForEach(options, id: \.self) {
                        Text($0)
                    }
                }
            }
        }
    }
}

In this example, the picker is placed inside a `Form` and grouped under a section header titled "Preferences." This layout is typical in settings screens, allowing users to select their preferences in a structured format.


Using Custom Views in Pickers


While the most common usage of a picker is with text options, you can use custom views within pickers to create more complex and visually rich selections. Here’s how to use images in a picker:



struct IconPickerView: View {
    @State private var selectedIcon = "star"
    let icons = ["star", "heart", "moon"]
    
    var body: some View {
        Picker("Select an icon", selection: $selectedIcon) {
            ForEach(icons, id: \.self) { icon in
                HStack {
                    Image(systemName: icon)
                    Text(icon.capitalized)
                }
            }
        }
        .pickerStyle(WheelPickerStyle())
    }
}

In this example, each picker option displays an icon alongside its name. This approach allows you to create more visually appealing pickers that align with your app’s design.


Conclusion


The `Picker` view in SwiftUI is a versatile component that can be customized to fit various use cases, from simple drop-down menus to complex selection interfaces with custom views. Understanding how to create and customize pickers will enable you to build intuitive and user-friendly selection controls in your SwiftUI applications.


SwiftUI’s `Picker` view provides a powerful and flexible way to create selection controls in your app. By mastering the different picker styles and customization options, you can design effective and attractive selection interfaces that enhance the user experience.


instructor

Exodai INSTRUCTOR!

Johan t'Sas

Owner and Swift developer!