Website Links

Friday, 11 December 2015

Swift - Creating a countdown timer

There are many situations where you may have the need to use a countdown timer. This article is aimed at helping you create one! Firstly, you will want to add a label to your storyboard and reference it through an @IBOutlet in the relevant view controller. This will display your countdown. Following that you will need the following code:

  class GameViewController: UIViewController {

    @IBOutlet var _timerLabel: UILabel!
    var _timer : NSTimer!
    ...

    override func viewDidLoad() {
      super.viewDidLoad()
      _timerLabel.text = "60"

      //the first argument is how long in seconds
      // target - where to look for the selector
      // selector - function name
      // userInfo - AnyObject, you can use this to store 
      // anything you need
      // repeats - whether or not the function should be 
      // repeatedly called
      _timer = NSTimer.scheduledTimerWithTimeInterval
       (1, target: self, selector: Selector("countDown"), 
       userInfo: nil, repeats: true)
    }

    // function called after time interval specified above
    // updates label, or stops timer and ends game if it 
    // has reached 0
    func countDown() {
      let currentCount = Int(_timerLabel.text!)
       
      if (currentCount == 0) {
        _timer.invalidate()
        gameOver()
      } else {
        _timerLabel.text = String(currentCount! - 1)
      }
    }

    ...

  }

For more information, view the reference page for NSTimer

No comments:

Post a comment