加载,在第二个视图控制器上保存高分

时间:2017-08-08 21:13:19

标签: ios swift uiviewcontroller

我正在尝试仅在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
    }
    
  3. 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       
    }
    

2 个答案:

答案 0 :(得分:1)

<强>首先

highScoreLabel = scoreGameOverLabel

应该是

 highScoreLabel.text = scoreGameOverLabel.text

其次,根据您的代码段,在GameOverViewController中没有addOne,您如何设置它并在If条件下使用它进行比较?

答案 1 :(得分: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")
}