通过UICollectionView传递数据

问题描述:

我一直在试图将数据从我的UICollectionViewController传递到我的UIViewController下的prepareForSegue()。我可以用的UITableView容易做到这一点:通过UICollectionView传递数据

override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
{ 
    if segue.identifier == "segue" 
    { 
     let detailViewController = ((segue.destination) as! DetailViewController) 
     let indexPath = self.tableView.indexPathForSelectedRow! 
     detailViewController.titleLabelText = titles[indexPath.row] 
    } 
} 

我已经经历了很多的问题和答案看,我尝试了多种解决方案,但他们都没有工作。以下是最新的东西我已经试过......

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    if let indexPath = self.collectionView?.indexPath(for: sender as! UICollectionViewCell) { 
     let detailViewController = segue.destination as! DetailViewController 
     detailViewController.titleLabelText = self.titles[indexPath.row] 
    } 
} 

但是,本我得到一个错误:

Could not cast value of type 'ProjectName.CollectionViewController' to 'UICollectionViewCell'.

如何做到这一点任何想法?

如错误所述,您的发件人的类型是UICollectionViewController而不是UICollectionViewCell。我认为你只需从你的collectionViewController中获得一个segue,这应该是你的collectionViewCell,然后检查你的viewController,然后重做segue。

我觉得方法:

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

你必须添加:

self.performSegue(withIdentifier: "Your Segue Name", sender: self) 

尝试将其更改为:

self.performSegue(withIdentifier: "Your Segue Name", sender: indexPath) 

然后在方法:

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

您可以直接从sender获得indexPath