我一直在尝试 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/