When to present a ViewController programatically

Posted by

While working on my app, I came across this scenario where I have a ViewController containing a UITableView. The UITableViewCell has a UIImage, tapping which opens another ViewController that presents a list of images to be selected. Phew…!!

To segue or not to segue!

Firstly, I tried adding a segue from the First VC to the Second VC. Calling a method when tapping UITapGestureRecognizer and then calling performSegue method:

performSegue(withIdentifier: "chooseicon", sender: sender)

and then:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { ...}

But that opens the Second VC even if I tap anywhere on the UITableViewCell.

I wanted the Second VC to be opened only when tapping the image in the cell, so in this scenario, I did not use segue and instead use Present for the new VC inside the Tap gesture method as shown in the Safe Present method:

if let iconVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "IconPickerVC") as? IconPickerVC
{
present(iconVC, animated: true, completion: {
iconVC.delegate = self
})
}

IconPickerVC is the second VC with the identity added in the Main.Storyboard as shown below:

IconPickerVC identity

You need to use Push when you’re using NavigationController. If you do not use NavigationController, simply use the Present way.

If you need to know how I set the image from the Second VC to the UITableViewCell of the First VC, check my post here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.