作者:blg1202702934392 | 来源:互联网 | 2022-10-22 03:30
In swiftUI
I discovered the Alert
type. But I wonder how to show it with the presentation
method.
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")
})
}
}
The binding is of type Binding
1> thisIsTheFox..:
.presentation()
在Beta 4中实际上已弃用。这是当前与.alert()
修改器一起使用的版本。
struct ContentView: View {
@State var showsAlert = false
var body: some View {
Button(action: {
self.showsAlert.toggle()
}) {
Text("Show Alert")
}
.alert(isPresented: self.$showsAlert) {
Alert(title: Text("Hello"))
}
}
}
2> tsp..:
您可以使用@State
变量作为绑定。或者,您可以使用使用的@EnvironmentObject
变量BindableObject
。
我认为你需要调用presentation
根视图得到它的工作,将其添加到Stack
,Group
等似乎并不工作。
这个片段似乎可以解决问题。请注意,@State
解除警报后,变量设置为false。
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"))
})
}
}
3> Kirit Modi..:
完整的警报代码,具有撤消和可采取的措施:
码:
import SwiftUI
struct ContentView: View {
@State private var isAlert = false
var body: some View {
Button(action: {
self.isAlert = true
}) {
Text("Click Alert")
.foregroundColor(Color.white)
}
.padding()
.background(Color.blue)
.alert(isPresented: $isAlert) { () -> Alert in
Alert(title: Text("iOSDevCenters"), message: Text("This Tutorial for SwiftUI Alert."), primaryButton: .default(Text("Okay"), action: {
print("Okay Click")
}), secondaryButton: .default(Text("Dismiss")))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
输出:
Output