Как инициализировать предупреждение в функции с помощью SwiftUI? - PullRequest
0 голосов
/ 05 марта 2020

Я пытаюсь добавить предупреждение при вызове gameOver(). Msgstr "Результат инициализатора '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")))
}

Ответы [ 2 ]

1 голос

В инфраструктуре 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
    }

}

с кодом выше вы достигнете этого:

enter image description here

0 голосов
/ 06 марта 2020

Это привело к тому, что игра перестала отображать предупреждение.

.alert(isPresented: $alertIsVisible) { () -> Alert in
    let roundedValue = sliderValueRounded()
    if self.round == 5 {
        return Alert(title: Text("Game Over"), message: Text("Your score was \(score)."), dismissButton: .default(Text("Play Again")) {
        self.startOver()
        })
    } else {
    return Alert(title: Text(alertTitle()), message: Text("The slider's value is \(roundedValue). \n" + "You scored \(pointsForCurrentRound()) points!"), dismissButton: .default(Text("Play Again")){
        self.changeTarget()
        self.round += 1
        })}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...