问题
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<Bool>
回答1:
You can use a @State variable as the binding. Alternatively you can use a @EnvironmentObject variable that uses a BindableObject.
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.
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"))
})
}
}
回答2:
.presentation() was actually deprecated in Beta 4. Here is a version that currently works with the .alert() Modifier.
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"))
}
}
}
回答3:
Full Code of Alert with dismiss and okay action:
Code:
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:
Output
回答4:
struct ContentView: View {
@State var aAlert = false
var body: some View {
Text("Alert").tapAction {
self.aAlert = true
}.presentation($aAlert, alert:{ Alert(title: Text("Alert"))})
}
}
回答5:
In addition to @tsp's answer, to display an alert with two buttons and handle button tap action, you can do as below:
@State var showAlert = false
var body: some View {
Button(action: {
self.showAlert = true
}) {
Text("Show Alert")
}
.presentation($showAlert) {
Alert(title: Text("Title"), message: Text("Message..."),
primaryButton: .default (Text("OK")) {
print("OK button tapped")
},
secondaryButton: .cancel()
)
}
}
Result:
来源:https://stackoverflow.com/questions/56448388/how-to-present-an-alert-with-swiftui