[英]Inform view that alert OK button is clicked in swiftUI
我创建了一个ViewModifier
来显示带有 2 个按钮的警报。 如何通知我的 ContentView 单击确定按钮,以便我可以执行按钮操作?
示例代码:ShowAlert 是我的自定义 ViewModifier
struct ShowAlert: ViewModifier {
@Binding var showingAlert: Bool
let title: String
let message: String
func body(content: Content) -> some View {
content
.alert(isPresented: $showingAlert) { () -> Alert in
Alert(title: Text(title), message: Text(message),
primaryButton: .default (Text("OK")) {
print("OK button tapped")
//How to trigger ok button clicked event to my content view
},secondaryButton: .cancel())
}
}
}
查看实施
ScrollView {
....
}.navigationBarTitle("Click")
.navigationBarItems(trailing: Button(action: {
self.showAlert = true
}) {
Image(systemName: "lock")
}.modifier(ShowAlert(showingAlert: $showAlert, title: "", message: "Are you sure you want to Logout"))
这是一个将回调传递给修饰符的解决方案演示。 使用 Xcode 11.4 / iOS 13.4 进行测试。
struct ShowAlert: ViewModifier {
@Binding var showingAlert: Bool
let title: String
let message: String
var callback: () -> () = {} // << here !!
func body(content: Content) -> some View {
content
.alert(isPresented: $showingAlert) { () -> Alert in
Alert(title: Text(title), message: Text(message),
primaryButton: .default (Text("OK")) {
print("OK button tapped")
self.callback() // << here !!
},secondaryButton: .cancel())
}
}
}
// Demo view
struct TestAlertModifier: View {
@State private var showAlert = false
@State private var demoLog = "Wait for alert..."
var body: some View {
NavigationView {
ScrollView {
Text(demoLog)
}.navigationBarTitle("Click")
.navigationBarItems(trailing: Button(action: {
self.showAlert = true
}) {
Image(systemName: "lock")
}.modifier(ShowAlert(showingAlert: $showAlert, title: "",
message: "Are you sure you want to Logout", callback: confirmAlert)))
}
}
private func confirmAlert() {
self.demoLog = "Tapped - OK"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.