2017-08-08 42 views
0

我想加載並保存我的高分只在gameOverViewController。我已成功將secondViewController的分數轉移到gameOverViewController。 gameOverViewController就像屏幕上的普通遊戲一樣,顯示你的分數,高分,並有重試和主菜單按鈕。我試圖設置highScoreLabel等於scoreGameOverLabel,它運行,但highScore int保持在0並且不等於gameOverScore。我想:加載,在第二個視圖控制器上保存高分

  1. 如果評分>高分,高分=得分
  2. 如果分數<高分,高分仍相同

    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  
} 

回答

1

SecondViewController中,嘗試設置您的最後一個分數。

gameOver.lastScore = addOne 

GameOverViewController添加lastScore變量,並跟蹤您的高分。

var lastScore = 0 
var highScore = UserDefaults.standard.integer(forKey: "high_score") 

if lastScore > highScore { 
    highScore = lastScore 
    UserDefaults.standard.set(highScore, forKey: "high_score") 
} 
+0

貯藏它到'UserDefaults'將保持用戶的高分,即使他們離開你的應用程序。你能顯示你收到的錯誤嗎? – gbhall

+0

你說得對,我有一個錯字。現在它在應用程序中保存我的分數和highScore,但是當我關閉應用程序時,highScore不會保存。 – ZDP

+0

你確定它沒有保存嗎? – gbhall

1

首先

highScoreLabel = scoreGameOverLabel 

或許應該

highScoreLabel.text = scoreGameOverLabel.text 

其次,按您的片斷,在GameOverViewController沒有addOne,你怎麼設置它並使用它來比較。如果條件?

+0

高分INT仍停留在0 – ZDP

+0

您沒有設置或初始化 –

+0

後的任意位置遞增高分的價值我更新的代碼,以便addOne =高分,但仍無法正常工作,並說高分是0 – ZDP

相關問題