高分标签未更新 - UserDefaults 和 Swift 4

High score Label not updating - UserDefaults and Swift 4

我从中获得此代码的资源是用 Swift 3 编写的并且可以正常工作。我的应用程序是用 Swift 4 编写的。我想我可能遗漏了 Swift 4 特有的东西,但我不知道它可能是什么。

我有合适的插座和变量...

@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var highScoreLabel1: UILabel!

var recordData: String!

viewDidLoadviewDidAppear占...

override func viewDidLoad() {
    super.viewDidLoad()

    let userDefaults = Foundation.UserDefaults.standard
    let value = userDefaults.string(forKey: "Record")
    recordData = value

}

override func viewWillAppear(_ animated: Bool) {
    let userDefaults = Foundation.UserDefaults.standard
    let value = userDefaults.string(forKey: "Record")

    if (value == nil) {
        highScoreLabel1.text = "0"

    } else {

        highScoreLabel1.text = value
    }
}

我创建了一个我认为可以工作的函数...

func high score () {

    if gameMode == 0 {

        if recordData == nil {

            let savedString = scoreLabel.text
            let userDefaults = Foundation.UserDefaults.standard
            userDefaults.set(savedString, forKey: "Record")

        } else {

            let score: Int? = Int(scoreLabel.text!)
            let record: Int? = Int(recordData)

            if score! > record! {

                let savedString = scoreLabel.text
                let userDefaults = Foundation.UserDefaults.standard
                userDefaults.set(savedString, forKey: "Record")

            }
        }
    }
}

保存时使用以下代码

DispatchQueue.main.async {
  userDefaults.set(savedString, forKey: "Record")
}

高分标签没有更新,因为没有代码。标签仅在 viewDidLoad / viewWillAppear.

中设置(一次)

强烈建议将高分保存为Int。这避免了选项,代码可以显着

减少
  • 声明recordData

    var recordData = 0
    
  • 删除viewDidLoad中的代码。在viewWillAppear中加载一次数据就足够了。

  • viewWillAppear替换为

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // integer(forKey returns 0 if the key is not used yet
        highScoreLabel1.text = String(UserDefaults.standard.integer(forKey: "Record"))
    }
    
  • 将高分替换为

    func highscore() {
        guard gameMode == 0, let score = Int(scoreLabel.text!), score > recordData else { return }
        recordData = score
        UserDefaults.standard.set(recordData, forKey: "Record")
        highScoreLabel1.text = String(recordData)
    }