我想在用户在表单选取器中 Select 某个内容时显示一个alert 框,然后用户必须在值更改之前确认其 Select .

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

我try 过使用onChange(),但理想情况下,判断应该在值更改之前进行.

推荐答案

如果您想在 Select 更改之前要求用户确认,则需要使用第二个var实现自定义绑定.这样,您就可以在必要时取消 Select .

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相关问答推荐

在列表项内的NavigationLink中的按钮无法正常工作

try 在小部件内部读取核心数据的SwiftUI总是返回空吗?

从AppKit打开SwiftUI设置

字典下标或运算符,如果密钥不存在,则添加指定的默认&值是SWIFT?

如何才能在同一线程上调用类中的每个方法,而不对每个调用使用同步块?

如何将函数参数(字符串文字)标记为可本地化?

如何在SwiftUI的文本视图中显示NSMutableAttributedString?

ToolbarItem 包含在动画中但不应该包含在动画中

SwiftUI 交易:根据外部状态制作一个动画或静止的按钮

避免 `(())` 显式指定 Void 类型的枚举关联值

如何在 SwiftUI 中创建条件内容?

PassthroughSubject 的 AsyncPublisher 值属性未生成所有值

如何在 ZStack 中单独下移卡片?

带有屏幕参数的 NSWindow 初始化程序在初始化时导致致命错误

Xcode:方法参数的代码完成

RealityKit – 无法加载 ARView(发现为零)

AVPlayer 在 iOS 15.4 中寻求 completionHandler 返回 false

如何在 SwiftUI 中实现 PageView?

Swift中switch 盒的详尽条件

Swift if 语句 - 多个条件用逗号分隔?