重新加载具有图像的UICollectionViewCell [英] Reload UICollectionViewCell which has image

查看:103
本文介绍了重新加载具有图像的UICollectionViewCell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建像Facebook NewsFeed这样的东西,我使用自定义 UICollectionViewCell 来显示来自JSON的数据(文本/图像)。我有2个不同的API。一个用于文本,另一个用于图像(每个单元格没有图像)。

I am trying to create something like Facebook NewsFeed where, I am using custom UICollectionViewCell to display data (Text/Image) from JSON. I have 2 different APIs. One for text and another for images(Every cell doesn't have image).

所以,首先,我从textAPI获取所有文本值到我的单元格中并重新加载myCollectionView。这非常有效。

So, First of all I am getting all text values in to my cells from my textAPI and reloading myCollectionView. That works perfect.

现在对于图像,我使用 ImageFetcher 来获取图像,

Now for the Images, I am using ImageFetcher to fetch images,

func ImageFetcher(postId : NSNumber, completion : ((_ image: UIImage?) -> Void)!) {

    var image = UIImage()

    let urlString = "http://myImageAPI/Image/\(postId)"
    let jsonUrlString = URL(string: urlString)
    print(urlString)
    URLSession.shared.dataTask(with: jsonUrlString!) { (data, response, error) in

        do {
            if let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String:Any] {
                if let images = jsonData["Image"] as? String {
                    if images == "" {
                        print("No Image")
                    } else {
                        let dataDecoded : Data? = Data(base64Encoded: images, options: .ignoreUnknownCharacters)
                        image = UIImage(data: dataDecoded!)!
                        completion(image)
                    }
                }
            }
            else {
                completion(nil)
            }
        } catch {
            print(error.localizedDescription)
        }
    }.resume()

}

要将图像显示在Cell中,

To display image in to Cell,

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

// Displaying other elements with text

DispatchQueue.main.async { 
        self.ImageFetcher(postId: self.myArray[indexPath.item].id!, completion: { (image) -> Void in
            customCell.mainImage.image = image
        })
// Declared "indexPaths" var indexPaths = [IndexPath]()
// Added this lines
      // let indexPath = IndexPath(item: indexPath.item, section: 0)
      // self.indexPaths.append(indexPath) 
    }

return customCell
}


override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    self.jsonParsing()

}
func jsonParsing() {
    //Fetching text data from textAPI

    //DispatchQueue.main.async {
    //      self.collectionView.reloadItems(at: self.indexPaths)
    //}
}

代码工作没有任何错误,但问题是图像只出现w我点击它们。 (我可以在单元格中看到空白/白色imageView,直到我点击它。一旦我点击imageView,图像就出现了)我觉得它有 DispatchQueue.main.async ,但不确定。

Code works without any error but the issue is Images only appears when I click on them. (I can see empty/white imageView in a cell until I click it. As soon as I click on imageView the Image appears) I feel its something with DispatchQueue.main.async but, not sure.

我不想在获取图像后重新加载整个collectionView。只想重新加载那些有Image的单元格。我在许多解决方案中找到
collectionView.reloadItemsAtIndexPaths(myArrayOfIndexPaths)
,但不知道如何在这种情况下使其工作。有人可以帮我吗?任何帮助将不胜感激。

I do not want to reload the whole collectionView after fetching the images. Just want to reload those cells which have Image. I found collectionView.reloadItemsAtIndexPaths(myArrayOfIndexPaths) on many solution but don't know how to make it work in this scenario. Can anyone please help me here? Any help will be much appreciated.

推荐答案

你能试试吗?

DispatchQueue.main.async {
      customCell.mainImage.image = image
 }

而不是

customCell.mainImage.image = image

============= ========更新======================

===================== Updated ======================

我最终帮助了Snehal不仅有图像加载问题,还有收集视图和图像缓存的其他几个问题。我建议他使用像SDWebImage这样的第三方库,但在响应中发现他的api返回图像为base64字符串。所以我只是继续清理他的代码并编写代码,我认为这是一个很好的字符串点,可以帮助他。

I ended up helping Snehal not only image load problem but also a couple of other issues with collection view and image caches. I suggested him to use a third party library like SDWebImage but found out his api returns image as base64 string in the response. So I just go ahead and clean up his code and write the code that I think it's a good string point that might help him.

import UIKit 

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { 

    let imageView = UIImageView() 
    lazy var collectionView: UICollectionView = { 
        let layout = UICollectionViewFlowLayout() 
        layout.minimumInteritemSpacing = 10 
        layout.minimumLineSpacing = 10 
        layout.scrollDirection = .vertical 

        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) 
        collectionView.delegate = self 
        collectionView.dataSource = self 
        collectionView.register(CustomCell.self, forCellWithReuseIdentifier: NSStringFromClass(CustomCell.self)) 
        collectionView.backgroundColor = .clear 
        return collectionView 
    }() 


    override func viewDidLoad() { 
        super.viewDidLoad() 
        view.addSubview(collectionView) 
    } 

    override func viewWillLayoutSubviews() { 
         super.viewWillLayoutSubviews() 
         collectionView.frame = view.bounds 
    } 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
        return 50 
    } 

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CustomCell.self), for: indexPath) as! CustomCell 
        cell.imageUrl = "http://myImageAPI/Image/\(postId)" 
        return cell 
    } 


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
         return CGSize(width: collectionView.frame.size.width - 2 * 20, height: 100) 
    } 

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 

} 
} 


class CustomCell: UICollectionViewCell { 

    let imageView = UIImageView() 
    var imageUrl: String? { 
        didSet { 
            if let imageUrl = imageUrl, let url = URL(string: imageUrl) { 
                dataTask = imageView.loadImage(url: url) 
            } 

        } 
    } 

    var dataTask: URLSessionDataTask? 

    override init(frame: CGRect) { 
        super.init(frame: frame) 

        backgroundColor = .white 
        imageView.backgroundColor = UIColor.lightGray 
        imageView.contentMode = .scaleAspectFit 
        contentView.addSubview(imageView) 
    } 

    required init?(coder aDecoder: NSCoder) { 
        fatalError("init(coder:) has not been implemented") 
    } 

    override func prepareForReuse() { 
        super.prepareForReuse() 
        dataTask?.cancel() 
        imageView.image = nil 
    } 

    override func layoutSubviews() { 
        super.layoutSubviews() 
        imageView.frame = bounds 
    } 
} 


extension UIImageView { 
    @discardableResult func loadImage(url: URL) -> URLSessionDataTask? { 
        if let image = ImageLoadManager.manager.cachedImages[url.absoluteString] { 
            self.image = image 
            return nil 
        } 
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in 
            do { 
                guard let data = data else { 
                    return 
                } 
                if let jsonData = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] { 
                if let images = jsonData["PostImage"] as? String {// Pase the Base64 image string
                     if images == "" { 
                          print("No Image") 
                     } else { 
                         if let dataDecoded = Data(base64Encoded: images, options: .ignoreUnknownCharacters), let decodedImage = UIImage(data: dataDecoded) { 
                             DispatchQueue.main.async { 
                   ImageLoadManager.manager.cachedImages[url.absoluteString] = decodedImage 
                   self.image = decodedImage 
                              } 
                         } 
                     } 
                 } 
             } 
             else { 
                  DispatchQueue.main.async { 
                      self.image = nil 
                  } 
             } 
            } catch { 
                 print(error.localizedDescription) 
            } 
        } 
        task.resume() 
        return task 
    } 
} 

class ImageLoadManager { 
    static let manager = ImageLoadManager() 
    var cachedImages = [String: UIImage]() 
}

这篇关于重新加载具有图像的UICollectionViewCell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆