【问题标题】:SwiftUI: Dismiss Alert ProgramaticallySwiftUI:以编程方式关闭警报
【发布时间】:2020-11-05 12:28:27
【问题描述】:

如果位置服务关闭或被拒绝,我会弹出一个警报,将用户引导至“设置”,以便可以打开位置服务。它通过将状态变量 showAlert 设置为 true 来显示。我的代码是:

Alert(title: Text("Location Services"),
                     message: Text("Location Services is off or denied. The app must have your location to function. Please enable Location Services for the app in Settings."),
                     primaryButton: .default(Text("Settings"), action: {
                        self.showAlert = false // my attempt to clear the alert
                        UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
                     }),
                     secondaryButton: .default(Text("Okay")))

我遇到的问题是,当用户单击设置按钮转到设置以打开定位服务时,警报不会消失。因此,当用户启用后返回应用程序时 他们,警报仍然存在,说明服务未开启。这是一种糟糕的用户体验,我希望在用户返回之前将其关闭。从代码中可以看出,我尝试将 showAlert 状态变量设置为 false,但这不起作用。有什么想法吗?

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    我认为这是由于应用程序变得不活跃,所以丢失了事件。试试下面的

     primaryButton: .default(Text("Settings"), action: {
        // delay action a bit, to give chance to close alert
        DispatchQueue.main.async {
           UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
        }
     }),
    

    【讨论】:

    • 谢谢!那成功了!我玩了延迟时间并将其一直降低到现在 + 0.01,它工作正常,没有明显的延迟。半秒感觉界面卡住了,以后有人用这个。
    • @Yrb,那么值得一试DispatchQueue.main.async { ... }
    • 也可以。那将值得编辑解决方案。节省几个周期,代码更干净。
    【解决方案2】:

    尝试使用这个开源:https://github.com/huynguyencong/ToastSwiftUI。我发现它非常好用。

    它适用于 Swift 5.0 或更高版本、iOS 13 或更高版本

    struct ContentView: View {
    @State private var isShowingToast = false
    
    var body: some View {
        VStack(spacing: 20) {
            Button("Show toast") {
                self.isShowingToast = true
            }
            
            Spacer()
        }
        .padding()
    
        // Just add a modifier to show a toast, with binding variable to control
        .toast(isPresenting: $isShowingToast, dismissType: .after(3)) {
            ToastView(message: "Hello world!", icon: .info)
        }
    }
    

    }

    【讨论】:

    • 欢迎来到 Stack Overflow。我不确定是否有充分的理由使用第三方包,当本地构建的工作完美而轻松时。而且你知道你在处理什么线程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 2019-10-24
    相关资源
    最近更新 更多