Search code examples
iosswifttimercountdown

Swift - Timer Countdown for gameplay


I have looked online at many different 'Timer' tutorials, but they are over-complicated with things like backgrounds e.t.c. What I would like is a timer at the top of the screen that counts down '3, 2, 1, Play'. I will have images instead of text. This timer is activated as soon as a touch - to - begin button is clicked (which I have already made). Any help you can give me to do this in Apple Swift would be very greatly appreciated.


Solution

  • Did you try the method scheduledTimerWithTimeInterval from NSTimer

    // IBOutlet From Storyboard
    @IBOutlet weak var imgView: UIImageView!
    
    var countdown : Int! = 0   // Variable to check the count down seconds
    
    override func viewDidLoad() {
          // Scheduling timer to Call the function **Countdown** with the interval of 1 seconds
          NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDown:"), userInfo: nil, repeats: true)
     }
    
     func countDown(timer: NSTimer) {
        countdown = countdown + 1   
        if (countdown == 1) {       // second 1, show image 3 
            imgView.image = UIImage(named: "three.png")
        }
        else if (countdown == 2) {  // second 2, show image 2
            imgView.image = UIImage(named: "two.png")
        }
        else if (countdown == 3) {  // second 3, show image 1
            imgView.image = UIImage(named: "one.png")
        }
        else if (countdown == 4) {  // second 4, show image 'play'
            imgView.image = UIImage(named: "play.png")            
        }
        else {
        // Invalidate the timer & remove the `time image` and continue with your `gameplay`
            imgView.removeFromSuperview()
            timer.invalidate()
        }
     }