SwiftUI - 仅设置一次状态变量后,警报显示两次 [英] SwiftUI - Alert displays twice after setting its state variable only once
本文介绍了SwiftUI - 仅设置一次状态变量后,警报显示两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想让这个按钮运行某个命令,如果它失败了,我想让它显示一个 Alert
说它失败了.它可以很好地执行此操作,除非警报显示时显示两次,但我只设置了一次.
I want to have this button run a certain command and if it fails, I want it to display an Alert
saying it failed. It does this fine except when the alert displays, it displays twice but I only set it once.
这是我用来显示警报的两个状态变量:
Here are the two state variables I use to display the 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)")
)
这是我的按钮:
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
}
推荐答案
如果强行将 self.alert 设为 false 会怎样?
What if you set false to self.alert forcibly ?
.alert(isPresented: self.$alert) {
self.alertView
}.onAppear{
self.alert = false
}
这篇关于SwiftUI - 仅设置一次状态变量后,警报显示两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文