Search code examples
iosobjective-cuiviewsegueuistoryboardsegue

perform segue from UIView


I have ViewController and there is UIView in it.

This UIView has separate class myView and there are many UI elements - one of them is CollectionView.

What I want is to perform segue when one of collection elements in myView is selected. But when I try to add line

performSegue(withIdentifier: "myIdintifier", sender: self)

to collection's view didSelectItemAt method I get error

Use of unresolved identifier 'performSegue'

And I understand that this is because I do it inside class that extends UIView and not UIViewController.

So how can I perfrom segue in this case? And also how can I prepare for segue?


Solution

  • Here I am going to evaluate it in step by step manner.

    Step - 1

    Create custom delegate using protocol as below snippet will guide you on your custom UIView. protocol must exist out of your custom view scope.

    protocol CellTapped: class {
        /// Method
        func cellGotTapped(indexOfCell: Int) 
    }
    

    Don't forgot to create delegate variable of above class as below on your custom view

    var delegate: CellTapped!
    

    Go with your collection view didSelect method as below

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            if(delegate != nil) {
                self.delegate.cellGotTapped(indexOfCell: indexPath.item)
            }
        }
    

    Step - 2

    Let's come to the your view controller. give the CellTapped to your viewcontroller.

    class ViewController: UIViewController,CellTapped {
    
        @IBOutlet weak var myView: MyUIView! //Here is your custom view outlet
        override func viewDidLoad() {
            super.viewDidLoad()
            myView.delegate = self  //Assign delegate to self
        }
    
        // Here you will get the event while you tapped the cell. inside it you can perform your performSegue method.
        func cellGotTapped(indexOfCell: Int) {
            print("Tapped cell is \(indexOfCell)")
        }
    }
    

    Hope this will help you.