0
我有一個應顯示照片的集合視圖。UIImageView不顯示UICollectionViewCell中的下載圖像
當我從Assets.xcassets顯示臨時圖像時,一切正常,但是當我從互聯網上下載圖像時,它不顯示任何內容。
CollectionViewController.swift
class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
@IBOutlet var collectionView: UICollectionView!
var currentCategory:PhotoCategory!
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return currentCategory.images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GalleryItemCollectionViewCell", for: indexPath) as! GalleryItemCollectionViewCell
cell.setGalleryItem(imageURL: currentCategory.images[indexPath.row].image)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let picDimension = self.view.frame.size.width/4.0
return CGSize(width: picDimension, height: picDimension)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let leftRightInset = self.view.frame.size.width/20.0
return UIEdgeInsetsMake(0, leftRightInset, 0, leftRightInset)
}
}
GalleryItemCollectionViewCell.swift
class GalleryItemCollectionViewCell: UICollectionViewCell {
@IBOutlet var itemImageView: UIImageView!
func setGalleryItem(imageURL:String) {
//itemImageView.image = #imageLiteral(resourceName: "tempImage2")
let url = URL(string: imageURL)
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async(execute: {
if let imageData = data {
if let image = UIImage(data: imageData) {
print("We do have the image")
self.itemImageView = UIImageView(image: image)
}
}
});
}
}
}
我確實看到 「我們確實有形象」 的輸出,所以下載完成,數據是一個UIImage。
如果我取消對該行:
//itemImageView.image = #imageLiteral(resourceName: "tempImage2")
並刪除以下異步,一切正常。
當我在ViewController中使用下載代碼來顯示一個正常的UiImageView它確實有效。
更新:
我最終加入了擴展的UIImageView到項目:
extension UIImageView {
func downloadedFrom(link:String, contentMode mode: UIViewContentMode) {
guard
let url = NSURL(string: link)
else {return}
contentMode = mode
URLSession.shared.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void 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(execute: {
self.image = image
});
}).resume()
}
}
,我將照片添加像這樣cellForItemAt:
cell.itemImageView.downloadedFrom(link: cell.photo.image, contentMode: .scaleAspectFill)