Sharonica
Sharonica

Reputation: 193

Swift: Pushing a View controller on a UICollectionViewCell

I have a collection view that each cell has a tap gesture, when tapped I want to launch another ViewController, like I would do when using a navigation bar (the ViewController has a X button that is supposed to pop it). I usually use self.navigationController?.present for this purpose, but in this case since it is a UICollectionViewCell, I cannot use present function. I tried this but it did not work:

    func handleTap(){
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "driver")
        self.window?.rootViewController?.presentedViewController?.addChildViewController(controller)
    }

For some reason it is all nil in the optionals. Is this even a logical approach? what would be a good solution to this problem?

Upvotes: 1

Views: 1167

Answers (1)

Rocky Balboa
Rocky Balboa

Reputation: 814

use this method to implement push segue.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // handle tap events
    print("You selected cell #\(indexPath.item)!")

}

You can also use storyboard to perform the action

Upvotes: 1

Related Questions