通知视图在swiftUI中单击警报确定按钮

时间:2020-05-22 11:52:33

标签: ios swift 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")) 

1 个答案:

答案 0 :(得分:1)

这里是将回调函数传递给修饰符的解决方案演示。在Xcode 11.4 / iOS 13.4上进行了测试。

demo

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"
    }
}