Search code examples
iosuinavigationcontrolleruinavigationbaruiprogressview

How to update UIProgressView below navigation controller properly?


My goal is progress bar below the navigation bar, which works absolutely fine as you can see on this screenshot:

enter image description here

Here is the code which creates this:

class NavigationController: UINavigationController {

    let progressView = UIProgressView(progressViewStyle: .Bar)

    override func viewDidLoad() {
        super.viewDidLoad()

        progressView.progress = 0.9
        view.addSubview(progressView)

        let bottomConstraint = NSLayoutConstraint(item: navigationBar, attribute: .Bottom, relatedBy: .Equal, toItem: progressView, attribute: .Bottom, multiplier: 1, constant: 1)
        let leftConstraint = NSLayoutConstraint(item: navigationBar, attribute: .Leading, relatedBy: .Equal, toItem: progressView, attribute: .Leading, multiplier: 1, constant: 0)
        let rightConstraint = NSLayoutConstraint(item: navigationBar, attribute: .Trailing, relatedBy: .Equal, toItem: progressView, attribute: .Trailing, multiplier: 1, constant: 0)

        progressView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraints([bottomConstraint, leftConstraint, rightConstraint])
        progressView.setProgress(0.8, animated: true)
    }
}

But when I am trying to update the progress value by pressing the upload button,

for value in [0.0, 0.25, 0.5, 0.75, 1.0] {
    NSThread.sleepForTimeInterval(0.5)
    let navC = navigationController as! NavigationController // shorthand
    navC.progressView.setProgress(Float(value), animated: true)
    let isMainThread = NSThread.isMainThread() // yes, it is main thread
    let currentValue = navC.progressView.progress // yes, the value is updated
}

nothing happens, but for the last value 1.0 suddenly the progress is full. What am I doing wrong?


Solution

  • var queue = dispatch_queue_create("a", nil)
    dispatch_async(queue, {
        for value in [0.0, 0.25, 0.5, 0.75, 1.0] {
            NSThread.sleepForTimeInterval(0.5)
    
            dispatch_async(dispatch_get_main_queue(), {
                let navC = navigationController as! NavigationController // shorthand
                navC.progressView.setProgress(Float(value), animated: true)
            })
        }
    })