gpt4 book ai didi

swift - 在选择器上显示警报选择 SwiftUI

转载 作者:行者123 更新时间:2023-12-03 08:04:06 26 4
gpt4 key购买 nike

我想在用户在表单选择器中选择某些内容时显示一个警报框,然后用户必须在值更改之前确认他们的选择。现在我的代码如下所示(仅来自一些教程):

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


}
}
}
}
}

我尝试过使用 onChange() 但理想情况下应该在值更改之前进行检查。

最佳答案

如果您想在选择更改之前要求用户确认,您需要使用第二个变量实现自定义绑定(bind)。这样您就可以在必要时取消选择。

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())
}
}
}

关于swift - 在选择器上显示警报选择 SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72993672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com