1

任何人都可以帮助我使用 CollectionView 吗?我从一些 API 中解析 JSON,并获取字符串值 - 标题和图像地址,然后将该数据分配给方法 cellForItem() 中的自定义 collectionViewCell。但是比我快速滚动集合视图,某些单元格可能包含错误的图像或重复的图像。我还在自定义单元格类中覆盖方法 prepareForReuse 并设置 cell.image = UIImage() ,但它没有用。请帮助我理解什么问题)对不起我的英语不好......

集合视图控制器

'''

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Result",
                                                      for: indexPath) as! ResultCell
        let film = results[indexPath.item]
        cell.name.text = film.title
        cell.imageView.layer.borderColor = UIColor(white: 0, alpha: 0.3).cgColor
        cell.imageView.layer.borderWidth = 2
        cell.imageView.layer.cornerRadius = 10
        cell.layer.cornerRadius = 10
        // setUp image for cell
        cell.imageView.image = nil
        contentManager.getImage(film.poster.image, cell.imageView)
        return cell
    }

'''

方法获取图像'''

func getImage(_ url_str:String, _ imageView:UIImageView) {
        let url:URL = URL(string: url_str)!
        let session = URLSession.shared
        let task = session.dataTask(with: url, completionHandler: {(data, response, error) in
            if data != nil {
                let image = UIImage(data: data!)
                if(image != nil) {
                    DispatchQueue.main.async(execute: {
                        imageView.image = image
                        imageView.alpha = 0
                        UIView.animate(withDuration: 1, animations: {
                            imageView.alpha = 1.0
                        })
                    })
                }
            }
        })
        task.resume()
    }

'''

单元格自定义类 '''

class ResultCell: UICollectionViewCell {
    @IBOutlet  var imageView: UIImageView!
    @IBOutlet var name : UILabel!
    
    
    override func prepareForReuse() {
       
        self.imageView.image = UIImage()
        self.name.text = nil
         super.prepareForReuse()
    }
}

'''

4

0 回答 0