How can I make a countdown with an NSTimer
using Swift?
Swift 4
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.updateTime), userInfo: nil, repeats: true)
Update function
@objc func updateTime(){
debugPrint("jalan")
}
import UIKit
class ViewController: UIViewController {
let eggTimes = ["Soft": 300, "Medium": 420, "Hard": 720]
var secondsRemaining = 60
@IBAction func hardnessSelected(_ sender: UIButton) {
let hardness = sender.currentTitle!
secondsRemaining = eggTimes[hardness]!
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:
#selector(UIMenuController.update), userInfo: nil, repeats: true)
}
@objc func countDown() {
if secondsRemaining > 0 {
print("\(secondsRemaining) seconds.")
secondsRemaining -= 1
}
}
}
Swift 3
private let NUMBER_COUNT_DOWN = 3
var countDownLabel = UILabel()
var countDown = NUMBER_COUNT_DOWN
var timer:Timer?
private func countDown(time: Double)
{
countDownLabel.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
countDownLabel.font = UIFont.systemFont(ofSize: 300)
countDownLabel.textColor = .black
countDownLabel.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)
countDownLabel.textAlignment = .center
self.view.addSubview(countDownLabel)
view.bringSubview(toFront: countDownLabel)
timer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(updateCountDown), userInfo: nil, repeats: true)
}
func updateCountDown() {
if(countDown > 0) {
countDownLabel.text = String(countDown)
countDown = countDown - 1
} else {
removeCountDownLable()
}
}
private func removeCountDownLable() {
countDown = NUMBER_COUNT_DOWN
countDownLabel.text = ""
countDownLabel.removeFromSuperview()
timer?.invalidate()
timer = nil
}