我正在尝试仅在gameOverViewController上加载并保存我的高分。我已成功将得分从secondViewController转移到gameOverViewController。 gameOverViewController就像一个普通的屏幕游戏,显示你的分数,高分并重试和主菜单按钮。我试图将highScoreLabel设置为scoreGameOverLabel,它运行,但highScore int保持为0并且不等于gameOverScore。我想:
如果得分<高分,高分仍然相同
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
}
答案 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")
}