我在UITableViewCell中有一个UICollectionView,我的缓冲区中有图像url,我想下载并在我的CollectionView中显示图像。
但不知道为什么显示无法读取数据 以下是我的代码: -
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BrandImagesCell", for: indexPath) as! BrandImagesCell
//let StrUrl = NSURL(string: self.arrImages[indexPath.row])! as URL
let urlPath: String = self.arrImages[indexPath.row]
let StrUrl: NSURL = NSURL(string: urlPath)!
cell.brandImage.downloadedFrom(url: StrUrl as URL, contentMode: .scaleToFill)
return cell
}
下载图片的方法: -
extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() { () -> Void in
self.image = image
}
}.resume()
}
}
我的数组中有所有图片网址(self.arrImages) 我该怎么做才能下载在collectionView中显示它? 感谢