2017-08-26 136 views
0

我一直在試圖將數據從我的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'.

如何做到這一點任何想法?

回答

1

如錯誤所述,您的發件人的類型是UICollectionViewController而不是UICollectionViewCell。我認爲你只需從你的collectionViewController中獲得一個segue,這應該是你的collectionViewCell,然後檢查你的viewController,然後重做segue。

0

我覺得方法:

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