如何使用swiftUI呈现警报

编程入门 行业动态 更新时间:2024-10-28 21:23:50
本文介绍了如何使用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才能使其正常运行,然后将其添加到Stack,Group等中.

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呈现警报

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

发布评论

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

>www.elefans.com

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