我有一个增加分数的按钮,如果它是最高分,那么即使在应用程序关闭并再次打开后,该数字也会保存为最高分。
那部分工作正常,但在我重新打开应用程序并单击按钮后,我的高分被重置并变得等于分数。我认为这是因为我在应该调用我的 HighscoreDefault 时调用了我的 highscore 变量,但我不明白你如何访问该值......如果这就是问题的话。
如何在应用程序重新打开后防止高分变为低于自身的值?
import UIKit
class ViewController: UIViewController {
let phrase = "Your Score: "
var increasingNum = 0
let otherphrase = "High Score: "
var highscore = 0
var label: UILabel?
var otherlabel: UILabel?
let HighscoreDefault = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: self.view.frame.size.width / 2 - 100, y: 100, width: 200, height: 20))
label.textAlignment = .center
label.text = "\(phrase) \(increasingNum)"
self.view.addSubview(label)
self.label = label
let otherlabel = UILabel(frame: CGRect(x: self.view.frame.size.width / 2 - 100, y: 200, width: 200, height: 20))
otherlabel.textAlignment = .center
otherlabel.text = "\(otherphrase) \(highscore)"
self.view.addSubview(otherlabel)
self.otherlabel = otherlabel
let button = UIButton(frame: CGRect(x: self.view.frame.size.width / 2 - 150, y: self.view.frame.size.height / 2 - 50, width: 300, height: 100))
button.backgroundColor = UIColor.cyan
button.addTarget(self, action: #selector(scoreGoUp), for: .touchUpInside)
self.view.addSubview(button)
if let highscore = HighscoreDefault.value(forKey: "highscore") {
otherlabel.text = "\(otherphrase) \(highscore)"
}
}
func scoreGoUp (sender: UIButton){
increasingNum += 1
self.label?.text = "\(phrase) \(increasingNum)"
if (increasingNum > highscore){
highscore = increasingNum
self.otherlabel?.text = "\(otherphrase) \(highscore)"
HighscoreDefault.set(highscore, forKey: "highscore")
}
}
}
最佳答案
在我看来,保存 highscore
最方便的方法是实现一个计算变量,如下所示:
var highScore: Int {
get {
return UserDefaults.standard.integer(forKey: "highScore")
}
set {
UserDefaults.standard.set(newValue, forKey: "highScore")
}
}
这样,在您的 Controller 或单例中拥有该变量后,您就不会费心去考虑 UserDefaults
。
关于ios - swift 3 : How do you save a high score programmatically?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40374948/