Learn Courses My Dashboard

How to add logic to picker

How to add logic to picker for e.x if selection = to that condition send a notification after couple weeks

Are you using SwiftUI or UIKit?

Typically your logic will be triggered by a button, not by changing the picker, but you’ll grab the selected value of the picker to do something

I am using swift ui , but where I should declare the selected value , I am confused about this I would be thankful if you give some examples

Your picker would have a binding value that changes to the option selected so I assume that you have a @State variable declared for that purpose.

You could add an .onChange() modifier to your view which monitors that variable and executes some code passing in that value.

Here’s an example

struct PickerView: View {
    @State private var selectedIndex = 0
    @State private var selectedCity = "Your selected city is: "
    let locations = ["Mexico City",
                     "New York City",
                     "Los Angeles",
                     "Toronto",
                     "Chicago",
                     "Houston",
                     "Havana",
                     "Montréal",
                     "London",
                     "Philadelphia"]

    var body: some View {
        VStack(spacing: 40) {
            Picker("Select a city", selection: $selectedIndex) {
                ForEach(locations.indices, id: \.self) { index in
                    Text(locations[index]).tag(index)
                }
            }

            Text(selectedCity)

            Spacer()
        }
        .onChange(of: selectedIndex, perform: { index in
            changeCity(index: index)
        })
    }

    func changeCity(index: Int) {
        selectedCity = "Your selected city is: \(locations[index])"
    }
}

struct PickerView_Previews: PreviewProvider {
    static var previews: some View {
        PickerView()
    }
}

thank you !