2

My code below has no limits and eventually goes to the end of the progress view without stopping.

I would like the progress view to go to the end of the bar within 10 seconds in 1 second intervals.

import UIKit

class ViewController: UIViewController {

    @IBOutlet var progessV : UIProgressView!
    var progressValue : Float = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(update), userInfo: nil, repeats: true)
    }

    @objc func update(){
        progressValue += 0.01
        progessV.progress = progressValue

    }
    @IBAction func reset() {
        progressValue = 0
    }

}
Zev Eisenberg
  • 8,080
  • 5
  • 38
  • 82
  • If you want 1 second intervals, why is the timer setup to go off every 1/100th of a second? – rmaddy Jul 12 '18 at 20:17

2 Answers2

2

You must set the timer to 1s and add it to a variable to stop it when it arrives to ten seconds.

Your code become to something like this:

import UIKit

class ViewController: UIViewController {

@IBOutlet var progessV : UIProgressView!
var progressValue : Float = 0
var timer : Timer?

override func viewDidLoad() {
    super.viewDidLoad()
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)
}

@objc func update(){
    if (progressValue < 1)
    {
        progressValue += 0.1
        progessV.progress = progressValue
    }
    else
    {
        timer?.invalidate()
        timer = nil
    }
}
@IBAction func reset() {
    progressValue = 0
}
}
Kerberos
  • 4,036
  • 3
  • 36
  • 55
  • This looks good however in the reset button it is not restarting. Nothing changes. –  Jul 13 '18 at 01:34
  • I figured it out you just have to add progessV.progress = progressValue in func reset. –  Jul 13 '18 at 01:37
0

Your time interval should be 1, the documentation of scheduleTimer says:

The number of seconds between firings of the timer.

So make the time interval 1 second. You also need to replace:

progressValue += 0.01

with:

progressValue += 0.1

As mentioned by rmaddy, you also need to stop the timer in the appropriate time, one way to do that is to make timer a property of your class like this:

private var timer: Timer?

And initialize it in the way you did:

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)

And inside update method add the suitable code to stop the timer:

if progressValue == 1 {
    timer?.invalidate()
}
Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36
  • Please note that while this is generally correct, you also need to stop the timer at the right time and keep in mind that `Timer` isn't exact. I may take longer than 10 seconds but not less. – rmaddy Jul 12 '18 at 20:24