如何使用 SwiftUI 连续呈现两个警报视图

编程入门 行业动态 更新时间:2024-10-28 01:11:51
本文介绍了如何使用 SwiftUI 连续呈现两个警报视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在点击第一个警报视图的关闭按钮后立即显示第二个警报视图.

I want to immediately present the second alert view after click the dismiss button of the first alert view.

Button(action: { self.alertIsVisible = true }) { Text("Hit Me!") } .alert(isPresented: $alertIsVisible) { () -> Alert in return Alert(title: Text("\(title)"), message: Text("\n"), dismissButton:.default(Text("Next Round"), action: { if self.score == 100 { self.bonusAlertIsVisible = true } .alert(isPresented: $bonusAlertIsVisible) { Alert(title: Text("Bonus"), message: Text("You've earned 100 points bonus!!"), dismissButton: .default(Text("Close")))} }) )

但是,它给了我一个错误:Alert.Button"不能转换为Alert.Button?"如果我将此段置于dismissButton 的范围之外,它将覆盖之前的.alert.那么我该怎么做,我只想在单击第一个警报的关闭按钮后弹出第二个警报.谢谢.

However, it gives me an error of 'Alert.Button' is not convertible to 'Alert.Button?' If I put this segment out of the scope of dismissButton, it will override the previous .alert. So how can i do it, I just want to pop up the second alert after clicking the dismiss button of the first alert. Thanks.

推荐答案

出现(使用 Xcode 11.2 测试):

It appears (tested with Xcode 11.2):

  • 虽然没有记录,但不允许添加多个.alert 修饰符在一个视图构建器序列中 - 仅适用于最新
  • 不允许向EmptyView添加.alert修饰符,它不起作用完全
  • 我找到了@Rohit 提出的替代解决方案.在某些情况下,有很多警报,这可能会导致代码更简单.

    I've found alternate solution to proposed by @Rohit. In some situations, many alerts, this might result in simpler code.

    struct TestTwoAlerts: View { @State var alertIsVisible = false @State var bonusAlertIsVisible = false var score = 100 var title = "First alert" var body: some View { VStack { Button(action: { self.alertIsVisible = true }) { Text("Hit Me!") } .alert(isPresented: $alertIsVisible) { Alert(title: Text("\(title)"), message: Text("\n"), dismissButton:.default(Text("Next Round"), action: { if self.score == 100 { DispatchQueue.main.async { // !! This part important !! self.bonusAlertIsVisible = true } } })) } Text("") .alert(isPresented: $bonusAlertIsVisible) { Alert(title: Text("Bonus"), message: Text("You've earned 100 points bonus!!"), dismissButton: .default(Text("Close"))) } } } } struct TestTwoAlerts_Previews: PreviewProvider { static var previews: some View { TestTwoAlerts() } }

    更多推荐

    如何使用 SwiftUI 连续呈现两个警报视图

    本文发布于:2023-11-27 19:30:53,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1639313.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:视图   警报   如何使用   两个   SwiftUI

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!