SwiftUI:解除Alert时如何执行关闭?

Boo*_*unz 2 beta alert closures ios swiftui

我一直在尝试swiftUI并查看了该Ray Wenderlich教程 ...我注意到他们没有重新实现“ nextRound”功能...所以我尝试自己做。遇到问题(也许他们也这样做):

基本问题更为笼统:

使用swiftUI,如何在关闭警报时(用户单击“确定”时)触发功能。?

我试过使用Alert构造函数的dismissButton参数...

(还有View的.onDisappear方法,但我不知道如何将其应用于Alert视图。)

码:

import SwiftUI

struct ContentView: View {

    @State var shouldShowAlert: Bool = false

    // this never gets called
    func onAlertDismissed() {
        print("you will not see this in the console")
    }

    // this doesn't seem to work
    var dismissButton: some View {

        Button(action: {
            self.onAlertDismissed()
        }) {
            // Bilbo Baggins does not appear -- "OK" still shows
            Text("BILBO BAGGINS")
        }
    }

    var body: some View {

        VStack {
            Spacer()

            Button(action: {
                self.shouldShowAlert = true
            }) {
                Text("show the alert!")
            }
            Spacer()
        }.alert(isPresented: $shouldShowAlert, content: {

            // what to add here?
            Alert(title: Text("Alert:"), message: Text("press OK to execute onAlertDismissed()..."))

            // what I have tried and doesn't work:
            /*
             Alert(title: Text("Alert:"), message: Text("press OK to execute onAlertDismissed()..."), dismissButton: self.dismissButton as? Alert.Button)
             */


        })

    }
}
Run Code Online (Sandbox Code Playgroud)

Fab*_*ian 5

该按钮的构造略有不同。基本上,您必须使用from的静态工厂方法Alert.Button来构造它们并传递它们。

Alert(title: Text("Alert:"),
    message: Text("press OK to execute default action..."),
    dismissButton: Alert.Button.default(
        Text("Press ok here"), action: { print("Hello world!") }
    )
)

Alert(title: Text("Alert!"), message: Text("Message"),
    primaryButton: Alert.Button.default(Text("Yes"), action: {
        print("Yes")
    }),
    secondaryButton: Alert.Button.cancel(Text("No"), action: {
        print("No")
    })
)
Run Code Online (Sandbox Code Playgroud)