2

I'm trying to pass an Image from one view to another and my code doesn't seem to be working- it takes the user to the new view but the image isn't transferred over as well. Any help would be greatly appreciated!

So, here's a button called Post that takes the user to a new view.

@IBAction func postButton(sender: AnyObject) {

    performSegueWithIdentifier("toBrowsePage", sender: nil)


}

Then, in another file for the other view controller...

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "toBrowsePage" {


    var itemToAdd = segue.destinationViewController as! ListPage

    itemToAdd.postingImage.image = browsingImage.image

    }

}

3 Answers3

1

Never assign image directly from another ViewController like this:

itemToAdd.postingImage.image = browsingImage.image

But instead of doing that just pass the imageName to the next View Controller and create one instance into your nextViewController which holds this image name and after that you can assign that image with in ViewDidLoad method of other ViewController.

consider this example:

you can pass ImageName this way:

itemToAdd.imageName = "YourImageName"

In your nextViewController create an instance which hold this String:

var imageName = ""

In your ViewDidLoad method:

postingImage.image = UIImage(named: imageName)

Hope this will help.

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
0

Its because you are trying to set the image of UIImageView which is not there in memory so it will not be displayed.

Instead you need to pass only image object to next controller. Create on properly for your Image in next controller & then pass the image from this controller to next controller.

Nilesh Patel
  • 6,318
  • 1
  • 26
  • 40
0

In your ListPage ViewController define an UIImage

var newImage: UIImage?

Now In prepareForSegue:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

if segue.identifier == "toBrowsePage" {

      var itemToAdd = segue.destinationViewController as! ListPage
      itemToAdd.newImage = browsingImage.image
      }
    }

Now in ListPage ViewDidLoad method set Image:

postingImage.image = newImage
Hamza Ansari
  • 3,009
  • 1
  • 23
  • 25
  • This looks good but it's still not working. Is it perhaps my Post button in ListPage? Perhaps it gets called before prepareforsegue? @IBAction func postButton(sender: AnyObject) { performSegueWithIdentifier("toBrowsePage", sender: nil) } –  Jul 22 '15 at 07:06
  • In ListPage ViewDidLoad make a breakPoint and check whether your newImage is nil ? – Hamza Ansari Jul 22 '15 at 07:50