swift - 如何使用 SwiftUI 在函数中初始化警报?
问题描述
gameOver()
我正在尝试在被调用时添加警报。“'Alert' 初始化程序的结果未使用”。如何初始化我创建的警报?
func gameOver() {
round = 0
score = 0
self.changeTarget()
}
解决方案尝试:
func gameOver() {
round = 0
score = 0
self.changeTarget()
Alert(title: Text("Game Over"),
message: Text("Thanks for playing"),
dismissButton: Alert.Button.default( Text("Play Again")))
}
解决方案
在 SwiftUI 框架中,您有多个实现选项Alert
,例如:
func alert<Item>(item: Binding<Item?>, content: (Item) -> Alert) -> some View where Item : Identifiable
func alert<Item>(item: Binding<Item?>, content: (Item) -> Alert) -> some View where Item : Identifiable
这是使用第一个选项的简单示例:
struct GameOverAlert: View {
@State private var round = 0
@State private var score = 0
@State private var restartGame = false // variable for showing alert
var body: some View {
VStack {
Text("round: \(round)")
Text("score: \(score)")
HStack { // used this style just for brevity
Button(action: { self.score += 1 }) { Text("add score") }
Button(action: { self.gameOver() }) { Text("over game") }
}
Spacer() // only for presenting result
}
.alert(isPresented: $restartGame) {
Alert(title: Text("Your score is \(score)"), dismissButton: .default(Text("Play again")) {
self.playAgain()
})
}
}
// described logic here, but it should be in some ViewModel, etc
private func gameOver() {
restartGame = true
}
private func playAgain() {
score = 0
round = 0
}
}
使用上面的代码,您将实现此目的:
推荐阅读
- python - 对数图中的相同刻度
- chatbot - Rasa 阈值实现
- laravel - Nuxt Auth + Laravel Passport - 本地方案与护照提供者
- python - pygame按住lkey延迟
- javascript - 关于处理来自 DOM 事件的错误的问题
- r - “survival”包中的 survfit 函数出错:“strata(mf[ll]) 中的错误:所有参数的长度必须相同”
- python - 在多个数据帧中按相同序列查找行
- react-native - 带有 M1 芯片的 Mac 上的 react-native-plaid-link-sdk
- python - ModuleNotFoundError:没有名为“应用程序”的模块 [将 Django 部署到 AWS]
- reactjs - 反应 i18 在循环内翻译动态值