我有一个UIProgress视图,它需要60秒才能在屏幕上显示,但是如何将它设置在某个位置而不是将时间设置为“ var seconds = 60”呢? (不包括所有代码。)
import UIKit
class MinuteMeditation: UIViewController {
@IBOutlet weak var progressController: UIProgressView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
let savedTime = UserDefaults.standard.string(forKey: "time")
var seconds = 60 // THIS IS WHERE I WANT THE USER DEFAULTS ^
var timer = Timer()
var isTimerRunning = false
var resumeTapped = false
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
runTimer()
答案 0 :(得分:0)
一种方法是在UIViewController
生命周期的某个时刻分配值,例如,如果您想每次显示视图时都使用保存的值,则可以使用viewWillLoad
,或者viewLoaded
,如果您只想在系统首次加载视图时进行设置,例如...
class MinuteMeditation: UIViewController {
@IBOutlet weak var progressController: UIProgressView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
var seconds: TimeInterval = 60.0 // THIS IS WHERE I WANT THE USER DEFAULTS ^
var timer = Timer()
var isTimerRunning = false
var resumeTapped = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let savedTime = UserDefaults.standard.string(forKey: "time"), let time = Double(savedTime) {
seconds = time
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
runTimer()
}
}
请记住,这将始终覆盖先前设置的任何值。如果您希望仅在以前未设置过该值的情况下使用保存的值,则需要将seconds
设为可选,并在以前未设置且没有保存的值的情况下分配默认值< / p>
另一种选择是使seconds
为计算值...
class MinuteMeditation: UIViewController {
@IBOutlet weak var progressController: UIProgressView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
var seconds: TimeInterval {
guard let savedTime = UserDefaults.standard.string(forKey: "time"), let time = Double(savedTime) else {
return 60.0
}
return time
}
var timer = Timer()
var isTimerRunning = false
var resumeTapped = false
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
runTimer()
}
}
这确实意味着该值永远不会直接设置,只能通过UserDefaults