我試圖從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
}
如何。我可以這樣做嗎?你能告訴我一個鏈接或水手嗎??或者至少需要什麼? –
在'cellForItemAt ...'裏面調用'self.reloadData()'?不應該那樣做。正確的答案是使用DispatchQueue.main.async。 – nathan
@rexhin上面鏈接的問題標記爲「可能的重複」,包含您需要的所有信息。 – nathan