首页 > 解决方案 > 如何使用 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")))
}

标签: swiftswiftui

解决方案


在 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
    }

}

使用上面的代码,您将实现此目的:

在此处输入图像描述


推荐阅读