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 delegate
and 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.
One thought on “Return selected image to Previous ViewController”