Search code examples
swiftxcodeuicollectionviewsegueuicollectionviewcell

CollectionView within a CollectionView: Using didSelectItemAt to performSegue


I have a collectionView within a collectionView and I want to be able to select a cell in the 2nd collectionView to perform a segue to another ViewController.

Currently, when I select a cell, I get the following message: " Receiver ... has no segue with identifier 'ToVC2'. "

However, I have used this segue/identifier from other UIButtons and it works.


I have two ViewControllers: ViewController1 and ViewController2.

On ViewController1, there is a collectionView ("categoryCollectionView") which has vertical scrolling.

Within categoryCollectionView, there is another collectionView ("eventCollectionView") which allows horizontal scrolling.

The two collectionViews are set up and working correctly for numberOfItemsInSection and cellForItemAt. I now want to be able to select a cell within eventCollectionView, and cause a segue from ViewController1 to ViewController2.

I have added a function in ViewController1:

func segueToViewController2(event: Event){

    performSegue(withIdentifier: "ToVC2", sender: event)

}

Within eventCollectionView's didSelectItemAt, I have tried the following:

var viewController1: ViewController1? = ViewController1()
viewController1.segueToViewController2(event: eventSelected)

When I select a cell, I get the following error message:

'Receiver () has no segue with identifier 'ToVC2''

However, this function performs the segue correctly if called from a regular UIButton on ViewController1 (therefore I know the issue is not that there is no segue / the identifier is wrong.) I believe the issue is that the function is being called from a collectionView within a collectionView.

Please help!!!!!


Solution

  • I believe the problem is that when you call var viewController1: ViewController1? = ViewController1(), you are initializing a new instance of ViewController1. This is probably not what you are meaning to do. Based on what you have said, you should pass a reference down the hierarchy of collection views you have created so that your didSelect can call the segue function on the original instance of ViewController1. Ideally, you would use a design pattern like delegation to do this.