Reputation: 137
I am trying to load and save my high score on only the gameOverViewController. I have successfully transferred the score from the secondViewController to the gameOverViewController. The gameOverViewController is like a normal game over screen that shows your score, high score and has retry and main menu button. I tried to set the highScoreLabel equal to the scoreGameOverLabel, it runs, but the highScore int stays at 0 and doesn't equal the gameOverScore. I am trying to:
if score < high score, high score remains same
var addOne = 0
class SecondViewController: UIViewController
{
@IBOutlet weak var score: UITextField!
score.text = "\(addOne)"
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let gameOver = segue.destination as! GameOverViewController
gameOver.gameOverText = score.text!
gameOver.lastScore = addOne
}
gameOverViewController
class GameOverViewController: UIViewController {
@IBAction func retryButton(_ sender: Any) {
addOne = 0
highScoreLabel.text = NSString(format: "%i", highScore) as String
}
@IBAction func mainMenuButton(_ sender: Any) {
addOne = 0
highScoreLabel.text = NSString(format: "%i", highScore) as String
}
var lastScore = 0
var highScore = UserDefaults.standard.integer(forKey: "high_score")
@IBOutlet weak var highScoreLabel: UILabel!
@IBOutlet weak var scoreGameOverLabel: UILabel!
var gameOver = ""
override func viewDidLoad() {
super.viewDidLoad()
if lastScore > highScore {
highScore = lastScore
highScoreLabel.text = NSString(format: "%i", highScore) as String
UserDefaults.standard.set(highScore, forKey: "high_score")
}
scoreGameOverLabel.text = gameOver
}
Upvotes: 0
Views: 60
Reputation: 13279
In SecondViewController
, try setting your last score.
gameOver.lastScore = addOne
In GameOverViewController
add the lastScore
variable and keep track of your high score.
var lastScore = 0
var highScore = UserDefaults.standard.integer(forKey: "high_score")
if lastScore > highScore {
highScore = lastScore
UserDefaults.standard.set(highScore, forKey: "high_score")
}
Upvotes: 1
Reputation: 2059
Firstly,
highScoreLabel = scoreGameOverLabel
Should probably be
highScoreLabel.text = scoreGameOverLabel.text
Secondly, as per your snippet, in GameOverViewController there is no addOne
, how are you setting it and using it to compare in If condition ?
Upvotes: 1