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

标签 ios swift uiimageview uicollectionview

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

相关文章:

ios - NSPredicate 无法解析格式字符串

iphone - 在哪里调用方法以重新加载应用程序从后台返回时的 View

swift - iOS/FCM - 如何使用有效载荷中的图像名称将 XCAsset 文件夹中的图像显示为通知附件?

ios - UIImageView 大小相对于屏幕大小

ios - 管理图像方向的最佳方法?

ios - Xcode std::__1::basic_ostream undefined symbol

ios - 当委托(delegate)不是 UIViewController 时不调用 UIImagePickerControllerDelegate 方法

ios - 如何正确推送到另一个导航 Controller

ios - MobAD 插页式退出后无法识别触摸 - Swift

ios - 是否可以为不同大小的 UIImageView 提供不同的图像