-2

I have a UIViewController with a UIImageView and a UIButton. When a user presses the button, a new UITableViewController appears with different rows, like "Animals", "Nature" and others. Then the user selects a row in didSelectRowAt and I present another UIViewController with pictures of animals, nature etc. Then a user selects a picture and I want to dismiss my controllers to the first one and put selected image there.

I don't want to store the image in Core Data nor User Defaults or somewhere else. I want to pass this image back somehow. How can I do that?

  • 1
    search for MVVM-C pattern ... – Jawad Ali May 06 '20 at 20:58
  • @jawadAli I'm already using MVC and it would probably be difficult to recode everything. Are there other ways? – sairy273 May 06 '20 at 21:09
  • 1
    There are [lots](https://stackoverflow.com/q/29734954/643383) [of](https://stackoverflow.com/q/24222640/643383) [duplicates](https://stackoverflow.com/q/5210535/643383). The specific facts that a) you're passing an image, and b) you're using Swift, don't really matter -- it'd be the same answer if you were passing an array of kittens in Objective-C. – Caleb May 06 '20 at 21:27

1 Answers1

2

Use the delegation approach to pass the selected image back.

protocol ImageInfoViewControllerDelegate: class {
    func didSelectImage(_ image: UIImage)
}

final class ImageInfoViewController: UIViewController {
    weak var delegate: ImageInfoViewControllerDelegate?
}

final class ListViewController: UIViewController, UITableViewDelegate, ImageInfoViewControllerDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let infoVC = ImageInfoViewController()
        infoVC.delegate = self
        present(infoVC, animated: true, completion: nil)
    }

    // MARK: - ImageInfoViewControllerDelegate
    func didSelectImage(_ image: UIImage) {
        // You have image here.
    }
}

Hayk Brsoyan
  • 186
  • 5
  • there is no connection between two classes sir – Jawad Ali May 06 '20 at 21:22
  • let infoVC = ImageInfoViewController() infoVC.delegate = self – Hayk Brsoyan May 06 '20 at 21:24
  • @HaykBrsoyan wouldn't present create the first controller on top of my third controller? And repeating this action will create tons of controllers. Shouldn't it be dismiss somehow? – sairy273 May 06 '20 at 21:51
  • You need to dismiss manual, ios don't dismiss View Controllers for you. https://developer.apple.com/documentation/uikit/uiviewcontroller/1621505-dismiss But this is an example of how you can use delegation. It does not matter you preset ViewController or Pushes in Navigation stack. – Hayk Brsoyan May 07 '20 at 06:38