简体   繁体   中英

swiftui change shown picker value

Hello I have made a picker in swiftUI where the user has to accept the change on the picker.

It works well, but there is one issue. If the user selects something and then declines the change, the shown value will still be what was selected though the actual value doesn't change.

If I open the picker again without selecting anything it reverts back to the right value but how to I do this without having to open the picker?

struct ContentView: View {
@State private var selectedColorIndex = "cd"
@State private var temp = ""
@State var alert = false

private var colors = ["ab", "cd", "ef", "gh", "ij", "kl", "mn", "op", "qr", "st", "uv", "wx", "yz"]
var body: some View {
    
    
    HStack {
        Text("Location")
        Picker("Location", selection: Binding(get: {selectedColorIndex}, set: {
            temp = $0
            alert = true
        })) {
            ForEach(colors, id: \.self) {
                Text($0)
            }
        }.pickerStyle(MenuPickerStyle())
        
    }.alert(isPresented: $alert) {
        Alert(title: Text("are you sure"), primaryButton: .default(Text("yes"), action: {
            selectedColorIndex = temp
            
            
        }), secondaryButton: .default(Text("no"), action: {
            
            //change shown value back to prev selectedColorIndex
        }))
    }
    
}

}

This does not work because the PickerView does not refresh with the value it gets from the binding. Adding a print statement in the binding confirms, that it indeed delivers the correct value.

A simple solution to this would be to force the Picker to refresh itself every time the body of the ContentView gets reavaluated. We can achieve this by manually changing the id of the Picker .

var body: some View {
    HStack {
        Text("Location")
        Picker("Location", selection: Binding(get: {selectedColorIndex}, set: {
            temp = $0
            alert = true
        })) {
            ForEach(colors, id: \.self) {
                Text($0)
            }
        }
        .id(UUID()) // add this
        .pickerStyle(MenuPickerStyle())
            
        
    }.alert(isPresented: $alert) {
        Alert(title: Text("are you sure"), primaryButton: .default(Text("yes"), action: {
            selectedColorIndex = temp
            
            
        }), secondaryButton: .default(Text("no"), action: {
            // No code needed here
            //change shown value back to prev selectedColorIndex
        }))
    }
}

If you want to know more why this works you can read my answer here: more info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM