如何正确更新导航控制器下方的UIProgressView?

时间:2015-12-30 10:25:48

标签: ios uinavigationcontroller uinavigationbar uiprogressview

我的目标是导航栏下方的进度条,如您在此屏幕截图中看到的那样工作正常:

enter image description here

以下是创建此代码的代码:

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

但是当我尝试通过按上传按钮来更新进度值时,

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
}

没有任何反应,但是对于最后一个值1.0突然进展已满。我究竟做错了什么?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您是否尝试在另一个线程上执行此操作以便像这样完美地更新它:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
           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
 }    
});