nycdanie nycdanie - 7 months ago 52
Swift Question

How to loop NSTimer in SWIFT with a specific number of counting

I am trying to loop a timer with a specific number of counting...
eg... 1, 2, 3, 4, 5

then loop again, the same counting, 10 times, then stop.

I was able to do the counting, but I can't do the looping of the counting.

What am I doing wrong?

var times = 0
var stopCounting = 10

@IBAction func buttonPressed(sender: UIButton) {
self.startTimer()
}

func startTimer(){
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("startCounting"), userInfo: nil, repeats: true)
}

func startCounting (){

times += 1
if times < stopCounting + 1{

if counter > -1 && counter < 6 {
counting.text = String(counter++)
} else if counter == Int(counting.text) {
counting.text = "0"
}

}

Answer
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var strTime: UILabel!

    var timer = NSTimer()
    var endTime: NSTimeInterval = 0
    var now: NSTimeInterval { return NSDate().timeIntervalSinceReferenceDate }
    var times = 0

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func updateText(){
        let time = Int(ceil(endTime - now))

        if time == 0 {
            times++
            if times == 10 {
                strTime.text = "end"
                timer.invalidate()
            }
            endTime = NSDate().timeIntervalSinceReferenceDate + 5
        } else {
            strTime.text = time.description
        }
    }

    @IBAction func buttonPressed(sender: UIButton) {
        timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateText", userInfo: nil, repeats: true)
        endTime = NSDate().timeIntervalSinceReferenceDate + 5
        sender.hidden = true
    }
}

to make it count from 1 to 5 you need to change from ceil to floor, abs() and add +1

func updateText(){
    let time = Int(floor(abs(endTime - now - 5)))
    if time == 5 {
        times++
        if times == 10 {
            strTime.text = "10" + "     " + "0"
            timer.invalidate()
        }
        endTime = NSDate().timeIntervalSinceReferenceDate + 5
    } else {
        strTime.text = times.description + "     " + (time+1).description
    }
}
Comments