【问题标题】:Load, save high score on second view controller在第二个视图控制器上加载、保存高分
【发布时间】:2023-03-20 13:38:01
【问题描述】:

我正在尝试仅在 gameOverViewController 上加载和保存我的高分。我已经成功地将分数从 secondViewController 转移到了 gameOverViewController。 gameOverViewController 就像一个普通的游戏结束屏幕,显示你的分数、高分,并有重试和主菜单按钮。我试图将 highScoreLabel 设置为 scoreGameOverLabel,它运行,但 highScore int 保持在 0 并且不等于 gameOverScore。我正在尝试:

  1. if score > high score , high score = score
  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       
}

【问题讨论】:

    标签: ios swift uiviewcontroller


    【解决方案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")
    }
    

    【讨论】:

    • 将其存储到UserDefaults 将保持用户的高分,即使他们离开您的应用程序也是如此。你能显示你得到的错误吗?
    • 你是对的,我有一个错字。现在它正在应用程序中保存我的分数和 highScore,但是当我关闭应用程序时,highScore 没有保存。
    • 你确定没有保存吗?
    • 是的,每次我双击主页并关闭应用程序时,highScore 都会重置为 0。
    • 如果您更新的代码反映了您所做的更改,您忘记将 highScore 更改为与我加载它的 var 相同...
    【解决方案2】:

    首先

    highScoreLabel = scoreGameOverLabel
    

    应该是

     highScoreLabel.text = scoreGameOverLabel.text
    

    其次,根据你的sn-p,在GameOverViewController中没有addOne,你是如何设置它并在If条件下使用它来比较的?

    【讨论】:

    • highScore int 仍然保持在 0。
    • 初始化后,您没有在任何地方设置或增加 highScore 的值
    • 我更新了代码,所以 addOne = highScore,但仍然无法正常工作并说 highScore 为 0
    猜你喜欢
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多