Swift 3将图像从URL添加到UIImageView

问题描述:

我试图从URL添加图像到UIImageView。我没有收到任何错误,但屏幕上没有显示任何内容。Swift 3将图像从URL添加到UIImageView

我在这里做错了什么?

我用.xcassets的图像使用了相同的方法,它工作正常,但它不是从远程URL工作。

这里是我的文件:

RelatedCollectionViewCell.swift

class RelatedCollectionViewCell: UICollectionViewCell { 

    @IBOutlet weak var related: UIImageView! 

} 

ViewController.swift

var images = [AnyObject]() 

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

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

    do { 
     try images.append(UIImage(data: Data(contentsOf: URL(string:"https://i.ytimg.com/vi/kWxHV9jkwSA/hqdefault.jpg")!))!) 
    } catch { 
     print(error) 
    } 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RelatedCollectionViewCell", for: indexPath) as! RelatedCollectionViewCell 

    cell.related.image = images[indexPath.row] as? UIImage 

    return cell 
} 

这不是在那个collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int)执行其内部零项的时刻,因为工作images阵列。 (因为您从一个至少需要一点时间的URL加载它们)。

所以,你必须让它重新加载你完成加入下载图片后:

collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    .... 
    self.reloadData() 
} 

或课程,你可以给它的项目的一个固定金额的部分,如果你知道正手这一数额:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return 5//whatever amount 
} 

当然,这将是更好的异步加载图像冻结您的应用程序时,没有互联网连接的存在阻止它,但是这不是问题的一部分。

+0

如何。我可以这样做吗?你能告诉我一个链接或水手吗??或者至少需要什么? –

+0

在'cellForItemAt ...'里面调用'self.reloadData()'?不应该那样做。正确的答案是使用DispatchQueue.main.async。 – nathan

+0

@rexhin上面链接的问题标记为“可能的重复”,包含您需要的所有信息。 – nathan

这是因为在第一次加载你的阵列images.count = 0

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

因为图片数组为空

,如果你的项目的数量为0,你的应用是不是在func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell进入。