user782400
user782400

Reputation: 1737

Pass image from one view controller to another controller gives nil

I am trying to send an image to the preview controller as shown below. My issue is that in the preview controller newImage is nil

Below is the code:

FirstViewController

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("In here")
    if segue.identifier == "showImage" {

        let secondViewController = self.storyboard!.instantiateViewController(withIdentifier: "showImage") as! showImageController

        secondViewController.newImage =  UIImage(named: imageArray[0])

    }
}

PreviewController

@IBOutlet weak var imageHolder: UIImageView!
var newImage: UIImage!

override func viewDidLoad() {
    super.viewDidLoad()
    imageHolder.image = newImage
    // Do any additional setup after loading the view.
}

Upvotes: 2

Views: 1640

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You should use segue.destination not create a new one , like this

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

   print("In here")

   if segue.identifier == "showImage" {

        let next = segue.destination as! showImageController

        next.newImage =  UIImage(named: imageArray[0])

    }

 }

Upvotes: 3

adamfowlerphoto
adamfowlerphoto

Reputation: 2751

instantiateViewController calls viewDidLoad() so you will not have setup your image when it gets called. Move the code to viewWillAppear() and it will work

Upvotes: 0

Related Questions