【问题标题】:How to pass download image to another view controller如何将下载图像传递给另一个视图控制器
【发布时间】:2018-04-15 15:39:48
【问题描述】:

我目前正在学习 iOS 开发,想知道如何在点击单元格后将下载的图像传递到另一个视图控制器以显示在那里。因此,用户将点击具有图像的单元格,然后另一个视图控制器会弹出该图像。我使用 URLSession 下载了图像,然后缓存了图像,这样用户就不会在每次向上或向下滚动到他们已经看到的另一个单元格时下载图像。我现在的问题是如何将下载的图像获取到另一个视图控制器?我试过了,但 videoController.thumbnailImageView.image 仍然返回为零。

let imageCache = NSCache<AnyObject, AnyObject>()

override func collectionView(_ collectionView: UICollectionView, 
didSelectItemAt indexPath: IndexPath) {
    let videoController = VideoController()
    let videoUrl = URL(string: Videos[indexPath.item].thumbnail_image_name)
    videoController.titleLabel.text = Videos[indexPath.item].title
    videoController.thumbnailImageView.image = self.imageCache.object(forKey: videoUrl as AnyObject) as? UIImage
    show(videoController, sender: Videos[indexPath.item])
}

这是我在 cellForItemAt indexPath 函数中缓存图像的方式。

DispatchQueue.main.async {

    let imageToCache = UIImage(data: data!)
    self.imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)

    cell.thumbnailImageView.image = UIImage(data: data!)
}

【问题讨论】:

    标签: swift swift4


    【解决方案1】:

    我想通了。对于任何想知道您必须这样做的人:

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! VideoCell
        let videoController = VideoController()
        videoController.titleLabel.text = Videos[indexPath.item].title
        videoController.thumbnailImageView.image = cell.thumbnailImageView.image
        show(videoController, sender: self)
    }
    

    您需要在所选索引路径上为单元格项目创建单元格。我不确定为什么缓存的方式不起作用,但是当我发现我会为其他想知道的人更新这个问题。

    【讨论】:

      猜你喜欢
      • 2015-10-13
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2012-05-02
      • 1970-01-01
      相关资源
      最近更新 更多