【发布时间】:2016-11-02 07:59:27
【问题描述】:
我有一个增加分数的按钮,如果它是最高分数,那么即使在应用程序关闭并再次打开后,该数字也会保存为最高分数。
这部分工作正常,但是在我重新打开应用程序并单击按钮后,我的高分被重置并等于分数。我认为这是因为当我应该调用我的 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")
}
}
}
【问题讨论】:
-
首先不要在
UserDefaults中使用valueForKey,除非你真的知道自己在做什么。有专门的方法integer(forKey: