1

我的目标是导航栏,你可以在这个截图中看到它的工作原理精绝下面的进度条:如何正确更新导航控制器下方的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 
} 

没有h出现,但最后一个值1.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) 
     }) 
    } 
}) 
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 
}  
}); 
+0

不工作。为什么它应该?与UI相关的东西必须在主线程中运行。 –

相关问题