Reputation:
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
}
}
Upvotes: 2
Views: 6675
Reputation: 4166
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
}
}
Upvotes: 2
Reputation: 6110
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()
}
Upvotes: 0