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

SwiftUI: How to execute closure when Alert is dismissed?

我一直在试用 swiftUI 并查看 this Ray Wenderlich tutorial...我注意到他们没有重新实现 "nextRound" 功能...所以我尝试自己做。 运行 遇到问题(也许他们也遇到了):

基本问题比较笼统:

使用 swiftUI,您如何在关闭警报时触发功能 - 当用户单击 "OK." 时?

我试过使用 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)
             */


        })

    }
}

通过查看您的代码,您似乎没有在警报属性中包含按钮,因此您的警报未执行任何操作,在 swiftui 中,警报签名为

init(title: Text, message: Text? = nil, primaryButton: Alert.Button, secondaryButton: Alert.Button)

正确实现签名是第一步

按钮的构造略有不同。您基本上必须使用 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")
    })
)

可以像这样创建警报:

import SwiftUI

struct ContentView: View {

@State var showingAlert = false

var body: some View {
    VStack {
        HStack { 
                Button(action: {
                    self.showingAlert = true
            })
            {
                Text("Save")
                    .font(.headline)
            }
            .alert(isPresented: $showingAlert, content: { 
                return Alert(title: Text("Save Product"), message: Text("Are you sure you want to save the changes made?"), primaryButton: .default(Text("Yes"), action: {
                    //insert an action here
                }), secondaryButton: .destructive(Text("No")))
                })
            }
        }
    }
}