如何在 swift ui 中显示两个警报,一个接着一个
Posted
技术标签:
【中文标题】如何在 swift ui 中显示两个警报,一个接着一个【英文标题】:How to show two alerts in swift ui one followed by the other 【发布时间】:2020-03-07 22:57:16 【问题描述】:我想制作一个用户按下一个按钮的应用程序,然后,当他们选择一个选项时,会弹出另一个警报。当我尝试类似的事情时;
struct ContentView: View
@State private var showingAlert = false
@State private var showingAlertII = false
var body: some View
Button(action:
self.showingAlert = true
, label:
Text("button")
.alert(isPresented: $showingAlert)
Alert(title: Text("Option one or two"), message: Text("choose"), primaryButton: .default(Text("one"), action:
// do some specific actions
self.showingAlertII = true
), secondaryButton: .default(Text("two"), action:
//do some other stuff
self.showingAlertII = true
))
.alert(isPresented: $showingAlertII)
Alert(title: Text("Option A or B"), message: Text("choose"), primaryButton: .default(Text("Split"), action:
// do something
), secondaryButton: .default(Text("B"), action:
//do something
))
)
没有显示警报。请注意,还有另一个教程:How can I have two alerts on one view in SwiftUI? 与此类似,但是,使用 .first 表示法并返回一个或另一个对我不起作用,因为我希望两个都显示,一个接一个。
【问题讨论】:
【参考方案1】:您不能在不覆盖其中一个的情况下直接在彼此后面进行两个 .alert 调用。关键是在单个 .alert 调用中获取所有逻辑。
import SwiftUI
enum ActiveAlert
case first, second, third
struct ContentView: View
@State private var showingAlert = false
@State private var activeAlert: ActiveAlert = .first
var body: some View
Button(action:
self.showAlert(.first)
, label:
Text("button")
.alert(isPresented: $showingAlert)
switch activeAlert
case .first:
return Alert(title: Text("First Alert"), dismissButton: .default(Text("Next"), action:
self.showAlert(.second)
))
case .second:
return Alert(title: Text("Second Alert"), dismissButton: .default(Text("Next"), action:
self.showAlert(.third)
))
case .third:
return Alert(title: Text("Third Alert"), dismissButton: .default(Text("Ok"), action:
//...
))
)
func showAlert(_ active: ActiveAlert) -> Void
DispatchQueue.global().async
self.activeAlert = active
self.showingAlert = true
【讨论】:
以上是关于如何在 swift ui 中显示两个警报,一个接着一个的主要内容,如果未能解决你的问题,请参考以下文章
多个 UIAlertController 在 Swift 中一个接一个地显示