所以我试图在这个应用程序中遵循mvc架构。这是图像部分的代码。
模型
import Alamofire
import AlamofireImage
class Brands {
private var _image : UIImage!
var image : UIImage {
if _image == nil {
_image = UIImage(named: "loadingImage")
}
return _image
}
init(BrandsDict : Dictionary<String, AnyObject>){
if let imageUrl = BrandsDict["imageUrl"] as? String{
Alamofire.request(imageUrl).responseImage(completionHandler: { (response) in
guard let image = response.result.value else {
self._image = UIImage(named: "loadingImage")
return
}
self._image = image
})
}else {
self._image = UIImage(named : "loadingImage")
}
查看
class BrandsCVCell : UICollectionViewCell {
@IBOutlet weak var BrandImage : UIImageView!
var brand : Brands!
func configureCell(_ brand : Brands){
self.brand = brand
BrandImage.image = self.brand.image
}
}
控制器
inViewDidLoad ....
if let jsonArray = data as? NSArray {
for objects in jsonArray {
let Brand = Brands(BrandsDict: objects as! Dictionary<String, AnyObject>)
self.Brands.append(Brand)
}
self.bestBrandCollection.reloadData()
}
....
if collectionView == BrandCollection {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BrandsCell", for: indexPath) as? BrandCollectionViewCell {
let Brand = Brands[indexPath.row]
cell.configureCell(Brand)
return cell
}else {
return UICollectionViewCell()
}
}
问题是当图像被加载到集合视图中时,显示的单元格不会获得下载的图像,但是当我滚动它们时,较早的单元格获取它们的图像。有人可以帮助我在下载后延迟加载图像。 (也许是完成处理程序,但我不知道放在哪里)。编码的答案将不胜感激。
答案 0 :(得分:1)
问题是下载后从网络下载的图像不会刷新到单元格。您需要在Alamofire.request
块中回调。解决方案:
首先,在模型中添加块回调:
class Brands {
//......
public var imageDidDownload:(()->Void)? //Key point, declare a callback block
init(BrandsDict : Dictionary<String, AnyObject>){
if let imageUrl = BrandsDict["imageUrl"] as? String{
Alamofire.request(imageUrl).responseImage(completionHandler: { (response) in
//......
self._image = image
self.imageDidDownload?() //Key point, callback after image downloaded
//......
})
}else {
//......
}
}
}
在单元格中,第二处理图像下载回调以刷新图像:
class BrandsCVCell : UICollectionViewCell {
//......
func configureCell(_ brand : Brands){
self.brand = brand
self.brand.imageDidDownload = { [weak self]() -> Void in
self?.BrandImage.image = self?.brand.image //Key point, refresh image to the imageView after downloading.
}
BrandImage.image = self.brand.image
}
}
尝试一下,应该可以。