如何在TableViewCell中为collectionView下载图像异步?

时间:2017-03-18 23:58:06

标签: uitableview asynchronous swift3 uicollectionview

我在tableViewCell中做了一个grid(collectionView),问题是每个单元格加载不同的图像。像这样制作一个Json:

{
   {
    "name": "Vegetales"
    "images": { imagesURLStrings }
   },
   {
     "name": "Frutas"
     "images": { imagesURLStrings }
   },
}

我使用this page自定义视图,使用this other进行异步下载。

我认为问题是因为,当我尝试为tableviewCell中的collectionView定义单元格数量时,分配错误,它不起作用,我不知道如何修复。

下载图片的代码:

func loadImages() {

    var section = 0
    var row = 0

    while (section < searchDataresults.count) {

        for i in searchDataresults[section].images {

            let key = section * 10 + row

            let imageUrl = i
            let url:URL! = URL(string: imageUrl)
            task = session.downloadTask(with: url, completionHandler: { (location, response, error) -> Void in
                if let data = try? Data(contentsOf: url){
                    // 4
                    DispatchQueue.main.async(execute: { () -> Void in
                        // 5
                        // Before we assign the image, check whether the current cell is visible

                        let img:UIImage! = UIImage(data: data)

                        saveImage(image: img, name: String(key))

                    })
                }
            })
            task.resume()
            row += 1
        }

        section += 1
        row = 0
    }

}

}

代码是我将图像放在collectionView上,记住它在tableViewCell中,所以单元格的数量必须根据json的images.count而改变。

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

    return searchDataresults[cellLoad].images.count
}

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellImage", for: indexPath as IndexPath)

    let key = cellLoad * 10 + indexPath.row

    if let img = loadImage(name: String(key)) {

        let imageView = UIImageView(image: img)
        imageView.frame = cell.frame
        imageView.bounds = cell.bounds
        imageView.center = cell.center

        cell.contentView.addSubview(imageView)

        print(key)

    } else {

        let imageView = UIImageView(image: UIImage(named: "emptyImg"))
        imageView.frame = cell.frame
        imageView.bounds = cell.bounds
        imageView.center = cell.center

        cell.contentView.addSubview(imageView)
    }

    return cell
}

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

子类UICollectionviewCell并重置集合视图单元格的内容

override func prepareForReuse() {
super.prepareForReuse()
self.customImageview.image = nil

 }