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

标签 ios closures alert swiftui beta

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

基本问题更笼统:

使用 swiftUI,您如何在解除警报时触发功能 - 当用户单击“确定”时。 ?

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

(还有 View 的 .onDisappear 方法,但我不知道如何将它应用于警报 View 。)

代码:

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)
             */


        })

    }
}

最佳答案

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

关于ios - SwiftUI:解除警报时如何执行关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57542343/

相关文章:

ios - Swift 问题 - NSUserDefault 和设置包没有响应

ios - SKScene 中未创建 SKLabelNode – Swift

ios - 带有条件 ViewController 的 Storyboard

animation - 快速访问函数内部闭包的变量

android - 从 AsyncTask 调用 AlertBuilder 时出现异常

javascript - 使用alertify.js 进行递归会导致自动关闭警报

css - 在 SweetAlert 上更改图标图像大小

objective-c - IOS:国家代码

java - 闭包意味着完全类型安全的标准?

python - 在 Python 中跟踪函数调用 + 闭包(à la SICP)的数量