我是新手(通常是编程人员),现在我正在一个项目中,我想在标签中显示时钟。
现在我的模型中有这个:
class CurrentDateAndTime {
let currentTime = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .MediumStyle)
}
然后在我的视图控制器中使用以下代码将其调用到标签中:
@IBOutlet weak var currentTimeLabel: UILabel!
let currentTime = CurrentDateAndTime()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
currentTimeLabel.text = currentTime.currentTime
}
问题是这不会在第二个时间间隔更新以显示实际时间。最后,我将需要在两个时间戳之间进行区别,以便我可以记录“开始时间”和“停止时间”之间的小时数。这甚至是最好/最简单的方法吗?关于我的目标的任何线索将不胜感激。
使用NSTimer
安排在您需要的时间间隔回调-在这种情况下,
tick()
在self
每一秒tick()
获取当前时间字符串并更新 UILabel
class MyViewController {
@IBOutlet weak var currentTimeLabel: UILabel!
var timer = NSTimer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
timer = NSTimer.scheduledTimerWithTimeInterval(1.0
target: self,
selector: #selector(tick),
userInfo: nil,
repeats: true)
}
@objc func tick() {
currentTimeLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(),
dateStyle: .MediumStyle,
timeStyle: .MediumStyle)
}
}
Swift 4.0更新:
class MyViewController : UIViewController {
@IBOutlet weak var currentTimeLabel: UILabel!
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.tick) , userInfo: nil, repeats: true)
}
@objc func tick() {
currentTimeLabel.text = DateFormatter.localizedString(from: Date(),
dateStyle: .medium,
timeStyle: .medium)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句