【发布时间】:2020-01-23 22:35:39
【问题描述】:
我希望将两个独特的警报附加到同一个 Button 视图。当我使用下面的代码时,只有底部的警报有效。
我在 macOS Catalina 上使用的是 Xcode 11 的官方版本。
@State private var showFirstAlert = false
@State private var showSecondAlert = false
Button(action: {
if Bool.random() {
showFirstAlert = true
} else {
showSecondAlert = true
}
}) {
Text("Show random alert")
}
.alert(isPresented: $showFirstAlert) {
// This alert never shows
Alert(title: Text("First Alert"), message: Text("This is the first alert"))
}
.alert(isPresented: $showSecondAlert) {
// This alert does show
Alert(title: Text("Second Alert"), message: Text("This is the second alert"))
}
我希望当我将showFirstAlert 设置为true 时显示第一个警报,我希望当我将showSecondAlert 设置为true 时显示第二个警报。只有第二个警报在其状态为真时显示,但第一个警报什么也不做。
【问题讨论】:
-
您永远不会将
showFirstAlert或showSecondAlert设置为false! -
@LinusGeffarth SwiftUI 在用户关闭警报时自动将它们设置为
false。 -
啊,我的错。感谢您的提醒!
-
当 SwiftUI 视图之一来自外部包并使用
.alert显示消息时,这尤其隐蔽。 (这让我想起了 UIKit 中UIAlertView的问题——并试图在视图控制器层次结构中的多个级别上使用它们)。