Search code examples
swiftuicollectionviewsegueuicollectionviewcelluistoryboardsegue

how to handle two collection view with push segues


I'm having two UICollectionView

@IBOutlet weak var collectionView1: UICollectionView!

@IBOutlet weak var collectionview2: UICollectionView!

i'm getting indexPath for each collection view separately with functions.

func getIndexPathForSelectedCell() -> NSIndexPath?
{

    var indexPath:NSIndexPath?

    if collectionview1.indexPathsForSelectedItems()!.count > 0 {
        indexPath = collectionview1.indexPathsForSelectedItems()![0]
    }
    return indexPath
}

func getIndexPathForSelectedCell2() -> NSIndexPath?
{

    var indexPath2:NSIndexPath?

    if collectionView2.indexPathsForSelectedItems()!.count > 0 {
        indexPath2 = collectionView2.indexPathsForSelectedItems()![0]
    }
    return indexPath2
}

I'm Performing segue for cell touch as follows.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
    if let indexPath = getIndexPathForSelectedCell()
    {

        let DealsdetailViewController = segue.destinationViewController as! DealsDetailViewController

        DealsdetailViewController.Dealsdata = Dealsdata[indexPath.row]
    }
    else if let indexPath2 = getIndexPathForSelectedCell2()
    {

        let ContainerviewController = segue.destinationViewController as! ContainerViewController

        ContainerviewController.BTdata = BTdata[indexPath2.row]
    }
}

if i click on a cell in first collection view segue performs correctly, when i click on a cell in second collection view

i got error in

let DealsdetailViewController = segue.destinationViewController as! DealsDetailViewController

which is first if statement condition value, i'm stuck here

please help me, how to handle performing both segue on cell click on each collection view.


Solution

  • Use the method from UICollectionView protocol

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let cell = cellForItemAtIndexPath(indexPath)!
        if collectionView == self.collectionView1 {
            self.performSegueWithIdentifier("segue1", sender: cell)
        } else if collectionView == self.collectionView2 {
            self.performSegueWithIdentifier("segue2", sender: cell)
        }
    }
    
    func prepareForSegue(segue: UIStoryBoardSegue, sender: AnyObject?) {
        if segue.identifer == "segue1" {
          let detailVC:DetailViewController = segue.destinationViewController as DetailViewController
          // Your sender is cell. You have indexPath of them and can get his identity in dataSource.
          //detailVC.name = ...
          //detailVC.surname = ...
        } else if segue.identifier == "segue2" {
          //...
        }
    }