Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

displaying alert on picker select SwiftUI

i want to display an alert box when a user selects something in a form picker the user then have to confirm their choice before the value changes.
right now my code looks like this(just from some tutorial):

            NavigationView {
            Form {
                Section {
                    Picker("Strength", selection: $selectedStrength) {
                        ForEach(strengths, id: \.self) {
                            Text($0)
                        
                            
                        }
                    }
                }
            }
        }

I have tried using onChange() but ideally the check should be before the value changes.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to ask the user to confirm before the selection changes you would need to implement a custom binding with a second var. With this you would be able to cancel the selection if necessary.

struct Test: View{
    @State private var selectedStrength: String = ""
    @State private var askForStrength: String = ""
    @State private var ask: Bool = false
    let strengths = ["1","2","3"]
    var body: some View{
        NavigationView {
            Form {
                Section {
                    Picker("Strength", selection: Binding(get: {selectedStrength}, set: {
                        //assign the selection to the temp var
                        askForStrength = $0
                        // show the Alert
                        ask = true
                    })) {
                        ForEach(strengths, id: \.self) {
                            Text($0)
                        }
                    }
                }
            }
        }.alert(isPresented: $ask) {
            // Here ask the user if selection is correct and apply the temp var to the selection
            Alert(title: Text("select?"), message: Text("Do you want to select \(askForStrength)"), primaryButton: .default(Text("select"), action: {selectedStrength = askForStrength}), secondaryButton: .cancel())
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading