Matthew Plays Matthew Plays - 1 year ago 199
Swift Question

Creating a Countdown Timer in Swift

I have wrote this code which counts down to a specific date.

How would I make it so that each element of the countdown is shown in a separate label.

So I would have a label that shows the number of days, a label to show the number of hours, a label to show the number of minutes and a label to show the number of seconds.


class ViewController: UIViewController {

@IBOutlet weak var dateLabelOutlet: UILabel!

let currentDate = Date()
let dateFormatter = DateFormatter()

let userCalendar = Calendar.current

let requestedComponent: Set<Calendar.Component> = [.day,.hour,.minute,.second]

override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(printTime), userInfo: nil, repeats: true)


func printTime()
dateFormatter.dateFormat = "dd/MM/yy hh:mm:ss"
let startTime = Date()
let endTime = "25/12/16 00:00:00")
let timeDifference = userCalendar.dateComponents(requestedComponent, from: startTime, to: endTime!)

dateLabelOutlet.text = "\(!) Days \(timeDifference.hour!) Hours \(timeDifference.minute!) Minutes \(timeDifference.second!) Seconds"

override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.


Answer Source

Your code already calculates the difference in DateComponents, and then builds a string with the day, hour, minute and second differences combined.

Just change this line:

dateLabelOutlet.text = "\(!) Days \(timeDifference.hour!) Hours \(timeDifference.minute!) Minutes \(timeDifference.second!) Seconds"

You'll need to create 4 labels and put in one, timeDifference.hour in another, timeDifference.minute in the third, and timeDifference.second in the 4th label.

If you wrote that code I would think that would be obvious - or is that somebody else's code that you copy/pasted?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download