简体   繁体   中英

Inform view that alert OK button is clicked in swiftUI

I have created a ViewModifier to show alert with 2 buttons. How to inform my ContentView that OK button is clicked, so that I can perform button action?

Sample code: ShowAlert is my custom 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())
        }
    }
}

View Implementation

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

Here is a demo of solution with passed callback into modifier. Tested with 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"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM