Search code examples
iosswiftswift4intervalsuiprogressview

Set max value on UIProgressView (swift 4)


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
    }

}

Solution

  • 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
    }
    }