|

How to Trigger Actions with Picker Selection in iOS SwiftUI

SwiftUI offers a wide range of UI components, and the Picker is one of the most useful among them. While it’s great for presenting a list of options to the user, you might also want to trigger an action when a selection is made.

In this blog post, we’ll explore how to execute actions based on Picker selection in SwiftUI.

What is SwiftUI Picker?

A Picker in SwiftUI is a UI element that allows users to select an option from a list. It can be presented in various styles, such as a wheel, a dropdown menu, or even custom views.

Why Trigger Actions on Selection?

Sometimes, you may want to perform an action when a user selects an option from the Picker. For example, you might want to update another UI element, make a network request, or change some internal state in your app.

How to Trigger Actions on Picker Selection

Create a State Variable

First, you’ll need a state variable to hold the selected value.

@State private var selectedOption = "Option 1"

Add the Picker

Add the Picker to your SwiftUI view.

Picker("Choose an option", selection: $selectedOption) {
    // Picker options here
}

Use the onChange Modifier

SwiftUI provides the onChange modifier to observe changes in state variables. Attach it to the Picker.

.onChange(of: selectedOption) { newValue in
    // Your action here
}

Implement the Action

Inside the onChange closure, you can implement whatever action you want to trigger.

.onChange(of: selectedOption) { newValue in
    print("User selected \(newValue)")
}

Complete Example

Here’s how it all comes together:

import SwiftUI

struct ContentView: View {
    @State private var selectedOption = "Option 1"

    var body: some View {
        Picker("Choose an option", selection: $selectedOption) {
            Text("Option 1").tag("Option 1")
            Text("Option 2").tag("Option 2")
            Text("Option 3").tag("Option 3")
        }
        .onChange(of: selectedOption) { newValue in
            print("User selected \(newValue)")
        }
    }
}

Triggering actions based on Picker selection in SwiftUI is straightforward, thanks to the onChange modifier. This allows you to make your app more interactive and responsive to user actions. Whether you’re updating the UI or fetching data, the onChange modifier has got you covered.

Similar Posts

Leave a Reply