Skip to content

Instantly share code, notes, and snippets.

@apatronl
Created July 25, 2020 16:18
Show Gist options
  • Save apatronl/cfedbc3f3882602c5a5b9a3133773198 to your computer and use it in GitHub Desktop.
Save apatronl/cfedbc3f3882602c5a5b9a3133773198 to your computer and use it in GitHub Desktop.
import SwiftUI
struct NumberGuessingGameView: View {
private var gameViewModel: NumberGuessingGame
@State private var guessLabel = "Guess the number!"
@State private var guess = ""
@State private var showAlert = false
public init(gameViewModel: NumberGuessingGame) {
self.gameViewModel = gameViewModel
}
var body: some View {
VStack {
Text(guessLabel)
TextField(
"Type a number",
text: $guess
)
.keyboardType(.numberPad)
.textFieldStyle(RoundedBorderTextFieldStyle())
.multilineTextAlignment(.center)
Button(
"Enter guess",
action: {
if let userGuess = Int(self.guess) {
self.gameViewModel.makeGuess(withNumber: userGuess)
self.guessLabel =
self.gameViewModel.status == .playing ? "Try again!" : "Guess the Number!"
self.showAlert = self.gameViewModel.status == .won || self.gameViewModel.status == .lost
}
self.guess = ""
}
)
.alert(isPresented: $showAlert) {
let title = gameViewModel.status == .won ? "You won! 🥳" : "You lost! 😢"
return Alert(
title: Text(title),
message: nil,
dismissButton: .default(Text("Start new game"), action: {
self.gameViewModel.reset()
})
)
}
}.padding()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment