Return selected image to Previous ViewController

Posted by

A very common scenario in an iOS App is to open another ViewController from one ViewController and return the value of the selected row to the previous ViewController and set the image e.g. setting an icon on the First ViewController.

You can perform the following steps to achieve this scenario:

1. Add a delegate variable on your second view controller. Please name it delegateand not Delegate as per naming convention.

weak var delegate: FirstVC?

2. Add functions to the First ViewController or create a protocol that the FirstVC will adhere to and that you want your second view controller delegate variable to perform.

extension FirstVC {
func selectedImage(_ imageName : UIImage) {
iconName = imgName
//Implement the logic to set image.
}
}

3. While pushing second view from first view controller, set your first view controller as delegate of second view controller. Something like this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "chooseicon" {
if let iconVC = segue.destination as? SecondVC {
iconVC.delegate = self
}
}
}

4. In your second view controller once image is selected call delegate of second view controller. e.g. use didSelectRowAt of UITableViewController as shown below:

let icons = [ "img1",  "img2",  "img3"]

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.delegate?.setSelectedImage(icons[indexPath.row])
self.dismiss(animated: true, completion: nil)
}

5. Implement logic for selectedImage in your first view controller and use the passed image as per Step 2.

Advertisements

One comment

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.