Jacob Cavin
Jacob Cavin

Reputation: 2329

Passing Data with UICollectionView

I've been trying to pass data from my UICollectionViewController to my UIViewController under the prepareForSegue(). I can do it easily with an UITableView:

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]
    }
}

I've looked through a lot of questions and answers, and I've tried multiple solutions, but none of them have worked. Here's the latest of what I've tried...

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]
    }
}

But, with this I am getting an error:

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

Any ideas on how to do this?

Upvotes: 0

Views: 114

Answers (2)

Amit
Amit

Reputation: 4896

I think in method:

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

you must be adding :

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

Try Changing it to :

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

Then in method:

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

you can get indexPath of the cell directly from sender

Upvotes: 0

思齐省身躬行
思齐省身躬行

Reputation: 181

As the error said, your sender is of type UICollectionViewController rather than UICollectionViewCell. I think you just make a segue from your collectionViewController, which should had to be your collectionViewCell, to your viewController, just check it and redo the segue.

Upvotes: 1

Related Questions