SwiftUI:如何在警报框关闭时执行闭包?

17
我一直在尝试使用swiftUI并查看了这个Ray Wenderlich教程... 我注意到他们没有重新实现"下一轮"功能... 所以我试着自己做。遇到了一个问题(也许他们也遇到了):
基本问题更普遍: 使用swiftUI,当Alert被解除时(当用户点击"确定"时),如何触发函数? 我尝试使用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)
             */


        })

    }
}
3个回答

27
的构造方式有些不同。您需要基本上使用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")
    })
)

啊,原来我应该使用 Alert.Button 而不是 Button。谢谢! - Nerdy Bunz

3

可以创建像这样的警报:

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

1

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

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

正确实现签名是第一步


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接