gpt4 book ai didi

ios - Swift 3 将图像从 URL 添加到 UIImageView

转载 作者:行者123 更新时间:2023-11-30 12:11:20 26 4
gpt4 key购买 nike

我正在尝试将 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
}

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

关于ios - Swift 3 将图像从 URL 添加到 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46018390/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com