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 mod
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());
}
}
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)
}
}