您好,我在swiftUI中创建了一个 Select 器,用户必须接受 Select 器上的更改.
它工作得很好,但有一个问题.如果用户 Select 某个内容,然后拒绝更改,则显示的值仍将是所选的值,尽管实际值没有更改.
如果我在没有 Select 任何内容的情况下再次打开选取器,它会恢复到正确的值,但如何在不打开选取器的情况下执行此操作?
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
}))
}
}
}