仅设置一次状态变量后警报显示两次

Luk*_*ers 5 swift swiftui

我想让这个按钮运行某个命令,如果失败,我希望它显示Alert失败的信息。它做得很好,除了当警报显示时,它显示两次,但我只设置一次。

以下是我用来显示警报的两个状态变量:

@State private var alert = false
@State private var alertView = Alert(
    title: Text("Well Hello There"),
    message: Text("You probably shouldn't be seeing this alert but if you are, hello there! (This is a bug)")
)
Run Code Online (Sandbox Code Playgroud)

这是我的按钮:

Button(action: {
    DispatchQueue.global(qos: .background).async {
        if let command = action.command {
            let error = Connection.shared.run(command: command)
            if error != nil {
                self.alertView = Alert(
                    title: Text("Failed to Run Action"),
                    message: Text("An error occurred while attempting to \(action.label).")
                )
                print("Displaying alert") // This only gets printed once
                self.alert = true
            }
        }
    }
}) {
    Text(action.label)
}.alert(isPresented: self.$alert) {
    self.alertView
}
Run Code Online (Sandbox Code Playgroud)

Arm*_*eni 1

好吧,我想我已经找到了问题所在,如果您将警报修饰符放入 a 中,forEach它实际上会由于某种原因触发两次。只需将其拿出来,它就会按预期工作。