将特定集合视图索引处的图像发送给另一个视图控制器的问题

问题描述:

我知道这可能看起来像是其他用户多次询问的问题。我确实经历了其中的很多,但我无法弄清楚我的问题的确切原因。将特定集合视图索引处的图像发送给另一个视图控制器的问题

我显示了一组图像集合视图中的一个url,它们存储在UIImage类型的数组中。现在,当我点击收藏视图时,该特定索引处的图像应显示在另一个viewcontroller中。

didSelectItemAt我这样做...

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
     self.thumbnailImage.image = self.arrayOfURLImages[indexPath.row] 
     performSegue(withIdentifier: "catalogueDetailIdentifier", sender: nil) 

} 

但在这行我得到一个崩溃说它意外地发现为零。因此,我无法前进。

另外在prepareForSegue,我已经这样做了......

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 

    if segue.identifier == "myIdentifier" { 

     if let targetVC = segue.destination as? DestinationViewController { 
      targetVC.myImage = photoThumbnail.image 

     } 
    } 
} 

但碰撞本身必须首先解决。任何帮助将不胜感激... :)

+0

你的问题似乎很容易解决。但是你需要提供更多的代码。你如何将图像放入数组中? –

+0

@Jonas Schafft这是我如何添加图像... self.arrayOfURLImages.append(self.sampleImageView.image!) –

+0

请做:print(indexPath.row)和print(self.arrayOfURLImages.count)并告诉我什么它打印 –

试试这个:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 

      self.thumbnailImage = UIImageView(frame:CGRectMake(0, 0, 100, 100)); 
      self.thumbnailImage.image = self.arrayOfURLImages[indexPath.row] 
      performSegue(withIdentifier: "catalogueDetailIdentifier", sender: nil) 

    } 

但请记住,你还需要的东西,如显示thumbnailImage:

self.view.addSubview(self.sampleImageView) 

更新:(因为我现在明白你只是想转让它)

var thumbnailImage: UIImage? 

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 

     self.thumbnailImage = self.arrayOfURLImages[indexPath.row] 
     performSegue(withIdentifier: "catalogueDetailIdentifier", sender: nil) 

} 

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 

    if segue.identifier == "catalogueDetailIdentifier" { 

    if let targetVC = segue.destination as? DestinationViewController { 
     targetVC.myImage = thumbnailImage! 

    } 
    } 
} 
+0

现在正在工作。非常感谢帮助... :) 也给了upvote也:) .. –

+0

可能更好地帮助D.M.做他想做的事情,而不是这个。如果在这里实例化一个UIImageView是没有意义的,如果他想要做的就是使用它来“携带”一个UIImage到另一个函数。 – DonMag

+0

我同意但是在这里没有看到他所有的代码都很难解释。 –