TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Trigger action from picker

Forums > SwiftUI

@flmcl  

I am having a lot of trouble figuring out how to trigger an action once a picker item is selected. The selector moves around ok but I cannot take action upon a selection being made. I want to refresh my map with new annotations. Anyone have some guidance on this? Thank you

Picker(selection: $myPick, label: Text("")) { ForEach(0..<mySpan.count) {index in Text(self.mySpan[index]).tag(index) }}

2      

The only way i know of is to use the .onReceive modifier on your Picker. As an example see the following code -

Picker("Select", selection: $name) {
            ForEach(names, id:\.self) { name in
                Text(name)
            }
        }
.onReceive([self.name].publisher.first()) { value in
            self.doSomethingWith(value: value)
 }

 // Just an example function below
 func doSomethingWith(value: String) {
        print(value)
  }

The .onReceive modifier (from the Apple Documentation) adds an action to perform on a particular view when this view detects data emitted by the given publisher. The publisher we are using above is the publisher associated with the @State property that i have used for the example. This @State property, as you can see, is the property that I have used for the selection value in the Picker.

From there we have a trailing closure for what we want to perform once we get that .first value from the publisher. You can choose to do whatever from there basically. In the above example i have just made a basic function and passed that .first value and printed it out. Now everytime the user moves that picker that function will be called.

As I said just a basic setup but im sure you can tweak it to get what you need.

Hope this helps

Dave

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.