Lea*_*ode 6 alert swift swiftui
我有以下代码:
@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())
}
}
Run Code Online (Sandbox Code Playgroud)
打印出以下输出:
我希望通过单击两个按钮之一来显示警报框并提示用户“取消”或“退出”;但它从不显示或提示用户,这是没有意义的!?
有没有人看到我的代码有什么问题!?这非常令人沮丧,因为它应该非常简单!?
Tom*_*ton 13
I had the same problem but realized this is now a deprecated .alert modifier. When I moved to using the newer modifier, it worked fine. Example from Apple's documentation:
.alert(title, isPresented: $didFail) {
Button("OK") {
// Handle acknowledgement.
}
} message: {
Text("Please ensure your credentials are correct.")
}
Run Code Online (Sandbox Code Playgroud)
com*_*m1x 10
感谢@ken-chin-purcell,他的回答帮助我找到了更方便的解决方法。
只需将警报放在 EmptyView 下即可:
.overlay(
EmptyView()
.alert(isPresented: $showAlert1) {
Alert(
title: ...,
message: ...,
...
)
},
alignment: .bottomTrailing
)
.overlay(
EmptyView()
.alert(isPresented: $showAlert2) {
Alert(
title: ...,
message: ...,
...
)
},
alignment: .bottomTrailing
)
Run Code Online (Sandbox Code Playgroud)
或者使用扩展:
extension View {
public func alertPatched(isPresented: Binding<Bool>, content: () -> Alert) -> some View {
self.overlay(
EmptyView().alert(isPresented: isPresented, content: content),
alignment: .bottomTrailing
)
}
}
Run Code Online (Sandbox Code Playgroud)
当视图层次结构中的视图上有一个 .alert(...) 视图修饰符时,我遇到了这个问题。如果父视图定义了 .alert() ,那么子视图的 .alert() 修饰符将不会显示它的警报。
就我而言,我将高级视图上的 .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"))
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2876 次 |
| 最近记录: |