如何获取日期和时间以在 UILabel 中显示时钟 [英] How to get date and time to show a clock in UILabel
问题描述
我是 swift 的新手(以及一般的编程),现在我正在从事一个项目,我想在标签中显示一个时钟.
I'm new to swift (and programming in general) and right now I'm working on a project that I'd like to display a clock in a label.
现在我的模型中有这个:
right now I have this in my model:
class CurrentDateAndTime {
let currentTime = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .MediumStyle)
}
然后在我的视图控制器中使用此代码将其调用到标签中:
and then call it into the label with this code in my view controller:
@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
}
问题是这不会以第二个时间间隔更新以显示实际时间.最终我将需要获得两个时间戳之间的差异,以便我可以记录开始时间"和停止时间"之间的小时数.这甚至是最好/最简单的方法吗?任何关于我的目标的线索将不胜感激.
The problem is this doesn't update on a second interval to show the actual time. And eventually I will be needing to get a difference between two time stamps so that I can log hours between a "start time" and a "stop time". Is this even the best/simplest way of doing it? Any clues toward my objective will be much appreciated.
推荐答案
使用 NSTimer
以您想要的时间间隔安排回调——在这种情况下,
Use NSTimer
to schedule the callbacks at your desired interval -- in this case,
- 每秒调用
tick()
self
tick()
获取当前时间字符串并更新UILabel
- call
tick()
onself
every second tick()
fetches the current time string and updates theUILabel
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 更新:
Swift 4.0 update:
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)
}
}
这篇关于如何获取日期和时间以在 UILabel 中显示时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!