Sharonica Sharonica - 4 years ago 173
Swift Question

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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download