在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呈现警报
发布评论