我有以下代码:
@State private var signoutAlert = false
var body: some View {
Button(action: {
self.signoutAlert = true
print("signout button clicked")
}) {
Text("Sign Out")
}
.alert(isPresented: $signoutAlert) {
print(".alert will display")
//
return Alert(title: Text("Sign Out"), message: Text("Are you sure you want to Sign Out?"), primaryButton: .destructive(Text("Sign Out")) {
print("Signing out....")
self.session.signOut()
self.presentationMode.wrappedValue.dismiss()
}, secondaryButton: .cancel())
}
}
打印出以下输出:我希望通过单击两个按钮之一来显示警报框并提示用户“取消”或“退出”;但它从不显示或提示用户,这是没有意义的!?
有没有人看到我的代码有什么问题!?这非常令人沮丧,因为它应该非常简单!?
最佳答案
当 View 层次结构中的 View 上有一个 .alert(...) View 修饰符时,我遇到了这个问题。如果父 View 定义了 .alert() ,那么 subview 的 .alert() 修饰符将不会显示它的警报。
在我的情况下,我将高级 View 上的 .alert() 向下移动为触发它的按钮上的修饰符,现在两个警报都正确显示。例如:
struct HiddenWalrusView: View {
@State private var showAlert1 = false
@State private var showAlert2 = false
var body: some View {
VStack {
Button("Show Alert One") { showAlert1 = true }
.padding(20)
Button("Show Alert Two") { showAlert2 = true }
.padding(20)
.alert(isPresented: $showAlert2) {
// This alert never displays
Alert(title: Text("I am the Walrus"))
}
}
.alert(isPresented: $showAlert1) {
Alert(title: Text("I am the Egg Man"))
}
}
}
struct EggmanAndWalrusView: View {
@State private var showAlert1 = false
@State private var showAlert2 = false
var body: some View {
VStack {
Button("Show Alert One") { showAlert1 = true }
.padding(20)
.alert(isPresented: $showAlert1) {
Alert(title: Text("I am the Egg Man"))
}
Button("Show Alert Two") { showAlert2 = true }
.padding(20)
.alert(isPresented: $showAlert2) {
Alert(title: Text("I am the Walrus"))
}
}
}
}
关于swift - SwiftUI 显示警报的问题 – 不会显示警报框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62748123/