在SDWebImage和UICollectionView中添加MBProgressHUD



我一直在尝试显示progressHUD时,我的细胞加载,它应该显示如何下载进度正在做。所以我把代码放在SDWebimage进度块获得下载进度,并将其传递到MBProgress HUD工作,但我不知道我在这里做错了什么!

let url = NSURL(string: (array[indexPath.row][0] as? String)!)
cell.imageView.sd_setImageWithURL(url, placeholderImage: nil, options: nil, progress: { (value1, value2) -> Void in
    self.HUD = MBProgressHUD(view: self.mycollectionView)
    self.view.addSubview(self.HUD)
    self.HUD.mode = MBProgressHUDMode.AnnularDeterminate
    self.HUD.delegate = self
    self.HUD.show(true)
    var x : Float = Float(value1)
    self.HUD.progress = x
    println(value1)
    println(value2)
    }, completed: block)

我也得到一个错误说:'MBProgressHUD needs to be accessed on the main thread.'

你只能从主线程更新UI,正如你的错误所说。下载图像是一个异步操作,不在主线程上执行,因此回调块不能更新UI -除非你在主线程上执行UI更新。要做到这一点,你必须使用gcd在主线程上执行你的代码,试试这个:

let url = NSURL(string: (array[indexPath.row][0] as? String)!)
cell.imageView.sd_setImageWithURL(url, placeholderImage: nil, options: nil, progress: { (value1, value2) -> Void in
dispatch_async(dispatch_get_main_queue(), {
    self.HUD = MBProgressHUD(view: self.mycollectionView)
    self.view.addSubview(self.HUD)
    self.HUD.mode = MBProgressHUDMode.AnnularDeterminate
    self.HUD.delegate = self
    self.HUD.show(true)
    var x : Float = Float(value1)
    self.HUD.progress = x
})
println(value1)
println(value2)
}, completed: block)

我认为这个外壳是在后台线程上调用的,你需要在

中包装HUD有关代码
dispatch_async(dispatch_get_main_queue()) {
         // hud here
    }

作为UI更改应该在主线程上执行。

其次,我认为外壳会被调用很多次(因为它正在显示进度),HUD视图每次都会被添加到子视图,所以你也需要照顾这个

如果您正在重用单元格,那么您可以在IB中添加活动指示器,然后将其类设置为HUDview或您想要的指示器。然后在collectionView cellForItemAtIndexPath方法中创建cell时添加startAnimating方法,然后在分配图像后检查完成闭包,您可以stopAnimating。

最新更新