Created
July 25, 2020 16:18
-
-
Save apatronl/cfedbc3f3882602c5a5b9a3133773198 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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