Search code examples
iosswiftxcodetimercountdown

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.

Code:

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() {
    super.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)
    timer.fire()

}

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

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

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

}


Solution

  • 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 = "\(timeDifference.day!) Days \(timeDifference.hour!) Hours \(timeDifference.minute!) Minutes \(timeDifference.second!) Seconds"
    

    You'll need to create 4 labels and put timeDifference.day 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?