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.
Use NSTimer
to schedule the callbacks at your desired interval -- in this case,
tick()
on self
every secondtick()
fetches the current time string and updates the 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 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)
}
}
This is a more current (2016) Swift example:
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var labelClock: NSTextField!
let dateFormatter = DateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .long
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateLabel), userInfo: nil, repeats:true);
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func updateLabel() -> Void {
labelClock.stringValue = dateFormatter.string(from: Date());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With