我正在制作下载应用程序并让用户通知我在主视图顶部使用UIView的进度。 我在更新标签和progressBars方面遇到了麻烦。 我尝试不同的方式来做:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// do some task
dispatch_async(dispatch_get_main_queue()) {
// update some UI
}
}
还有:
self.lblSpeedDownload.setNeedsDisplay()
但每次调用时都不会更新用户界面
所以我尝试了这个https://stackoverflow.com/a/26744884/2410264 现在它看起来像是我制作的最佳解决方案,但它仍然不够快速更新:它看起来越像我称之为更新功能,它就越需要它时间更新UI(1-2-10-20秒......)
这是我的代码:
一个类变量:
let source = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_main_queue());
开始下载时拨打电话:
dispatch_source_set_event_handler(source) {
[unowned self] in
self.updateDownloadView(self.mediaIndex, numberOfMedia: self.numberOfMedia)
}
dispatch_resume(source)
当我想要更新UI时调用:
dispatch_source_merge_data(source, 1);
更新功能:
func updateDownloadView(mediaIndex : Float, numberOfMedia:Int32){
if downloadPopup != nil {
var tempText:String
if self.selectedDirectories.count == 1 {
tempText = "Folder "
} else {
tempText = "Folders "
}
self.lblFolders.text = tempText + (self.downloadIndex+1).description + "/" + self.selectedDirectories.count.description + " :"
if numberOfMedia == 1 {
tempText = "Image "
} else {
tempText = "Images "
}
self.lblImages.text = tempText + Int(floor(mediaIndex)+1).description + "/" + numberOfMedia.description + " :"
let images_progress = mediaIndex/Float(numberOfMedia)
let folders_progress = Float(self.downloadIndex)+images_progress/Float(self.selectedDirectories.count)
self.progressFolders.setProgress(folders_progress, animated: true)
self.progressImages.setProgress(images_progress, animated: true)
self.lblSpeedDownload.text = Util.getByteString(self.downloadPopup.getDownloadSpeedBySecond())+"/s"
}
}
你发现我的代码有问题吗? 您还有其他更新UI的方法吗?
感谢您阅读我!