0

I am using an NSTimer to let the user know the app is working. The progress bar is set up to last 3 seconds, but when running, it displays in a 'ticking' motion and it is not smooth like it should be. Is there anyway I can make it more smooth - I'm sure just a calculation error on my part.

Here is the code:

import UIKit

class LoadingScreen: UIViewController {

    var time : Float = 0.0
    var timer: NSTimer?

    @IBOutlet weak var progressView: UIProgressView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do stuff

        timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector:Selector("setProgress"), userInfo: nil, repeats: true)

    } //close viewDidLoad

    func setProgress() {
        time += 0.1
        progressView.progress = time / 3
        if time >= 3 {
            timer!.invalidate()
        }
    }
}
Evgeny Karkan
  • 8,782
  • 2
  • 32
  • 38
Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38

1 Answers1

0

As per Apple iOS SDK docs you can achieve it with the use of next API:

func setProgress(_ progress: Float, animated animated: Bool)

It adjusts the current progress shown by the receiver, optionally animating the change.

Parameters:
progress - The new progress value.

animated - true if the change should be animated, false if the change should happen immediately.

More info on this:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIProgressView_Class/index.html#//apple_ref/occ/instm/UIProgressView/setProgress:animated:

So in your case you should do it like this:

func setProgress() {
    time += 0.1

    dispatch_async(dispatch_get_main_queue()) {
        progressView.setProgress(time / 3, animated: true)
    }

    if time >= 3 {
        timer!.invalidate()
    }
 }

Also please note that it is a good practice to perform UI updates on main thread, so I just dispatched progress update on main queue.
Hope it will help you.

Evgeny Karkan
  • 8,782
  • 2
  • 32
  • 38