如何使用swiftUI呈现警报 [英] How to present an Alert with swiftUI

查看:82
本文介绍了如何使用swiftUI呈现警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

swiftUI中,我发现了Alert类型.但是我想知道如何使用presentation方法显示它.

In swiftUI I discovered the Alert type. But I wonder how to show it with the presentation method.

初始化Alert非常简单.但是如何使用绑定?

Initializing an Alert is pretty easy. But how to use the binding?

struct ContentView : View {
    var body: some View {
        Button(action: {
            // Don't know how to use the `binding` below
            presentation(binding, alert: {
                Alert(title: Text("Hello"))
            })
        }, label: {
            Text("asdf")
        })
    }
}

绑定的类型为Binding<Bool>

推荐答案

您可以使用@State变量作为绑定.或者,您可以使用使用BindableObject@EnvironmentObject变量.

You can use a @State variable as the binding. Alternatively you can use a @EnvironmentObject variable that uses a BindableObject.

我认为您需要在根视图上调用presentation才能使其正常运行,然后将其添加到StackGroup等中.

I think you need to call presentation on the root View to get it to work, adding it to a Stack, Group, etc. doesn't seem to work.

此代码段似乎可以解决问题.请注意,解除警报后,@State变量将设置为false.

This snippet seems to do the trick. Note that @State variable is set to false after the alert is dismissed.

struct ContentView: View {

    @State var showsAlert = false

    var body: some View {
        Button(action: {
            self.showsAlert = true
        }, label: {
            Text("asdf")
        }).presentation($showsAlert, alert: {
            Alert(title: Text("Hello"))
        })
    }
}

这篇关于如何使用swiftUI呈现警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆