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相關的東西必須在主線程中運行。 –

相關問題