【发布时间】:2019-11-05 06:53:21
【问题描述】:
这是一个计时器应用程序,我希望计时器在应用程序被终止时暂停,当您重新打开应用程序时,我希望计时器显示最后一次已知时间。
我已经为要保存的数据设置了一个结构。
let defaults = UserDefaults.standard
private enum TimeData {
static let allCurrentTime = "allCurrentTime"
}
override func viewDidLoad() {
super.viewDidLoad()
checkForSavedTimer()
marksSavedData()
theTimer.text = "00:00:00"
theTimer.font = UIFont(name: "Menlo-BoldItalic", size: 40)
marksTableView.isHidden = false
}
//I set the timer info to the struct (see below)
@objc func updateTimerLabel() {
seconds += 1
if seconds == 60 {
minutes += 1
seconds = 0
}else if minutes == 60 {
hours += 1
minutes = 0
}
timerString = "\(hours):\(minutes):\(seconds)"
theTimer.text = timerString
defaults.set(theTimer.text, forKey: TimeData.allCurrentTime)
}
// I then created a function which I called in the viewdidload above
func checkForSavedTimer() {
let allCurrentTime = defaults.value(forKey: TimeData.allCurrentTime) as? String ?? ""
theTimer.text = allCurrentTime
}
我认为这会将来自 theTimer 的字符串保存到 UserDefaults,然后在 viewDidLoad 中将其取出并保存到“theTimer.text”,但结果是 00:00:00
【问题讨论】:
-
只需在 viewDidLoad 函数的末尾添加 checkForSavedTimer() 而不是开头
标签: swift xcode4 userdefaults