ios - swift 3 : How do you save a high score programmatically?

标签 ios iphone swift swift3

我有一个增加分数的按钮,如果它是最高分,那么即使在应用程序关闭并再次打开后,该数字也会保存为最高分。

那部分工作正常,但在我重新打开应用程序并单击按钮后,我的高分被重置并变得等于分数。我认为这是因为我在应该调用我的 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/

相关文章:

ios - 如何获取请求中 header 的值(URLSession.shared.dataTask(带有 : request) { (data, 响应,错误)

ios - 在自动布局环境中移动 UIView

iphone - 在未初始化的对象(空指针)上调用方法

ios - 与 WatchKit 应用程序的行为不一致 - Swift

Swift - 有没有办法在不抛出错误的情况下匹配错误?

ios - Swift prepareForSegue 取消

ios - UIview下的UIButton无法触摸

ios - 具有播放/暂停控件和画中画功能的视频播放器,就像 Safari 中一样

ios - SKProductsRequest 导致崩溃 - Cocos2d 和应用内购买

ios - 如何确定 swift firebase 节点是否更新