很抱歉,如果这是一个新手问题,我对iOS&迅速。我已经在互联网上看到如何使用用户默认值,但我不知道如何将其插入我的项目中:
@IBOutlet weak var labelScore: UILabel!
var score = 0
let scoreUserDefault = UserDefaults.standard
@IBAction func button(_ sender: Any) {
score += 1
labelScore.text = String(score)
print(score)
}
override func viewDidLoad() {
super.viewDidLoad()
if let score = scoreUserDefault.value(forKey: "best") as? Int {
self.score = score
}
}
我的项目没有存储得分,我预计会这样做。
答案 0 :(得分:0)
欢迎来到swift
//你应该先存储价值
//这里也是一个很好的教训 https://www.hackingwithswift.com/example-code/system/how-to-save-user-settings-using-userdefaults
@IBOutlet weak var labelScore: UILabel!
var score = 0
let scoreUserDefault = UserDefaults.standard
@IBAction func button(_ sender: Any) {
score += 1
labelScore.text = String(score)
// you should store value sta key
scoreUserDefault.set(score, forKey: "best")
print(score)
}
override func viewDidLoad() {
super.viewDidLoad()
if let score = scoreUserDefault.integer(forKey: "best"){
self.score = score
}
}