问题描述
在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呈现警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!