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

    }

}
2
  • Is the postingImage nil? Commented Jul 22, 2015 at 5:37
  • no. when i run the app on my phone, I'm uploading an image so it can't be nil. Commented Jul 22, 2015 at 5:38

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

2 Comments

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) }
In ListPage ViewDidLoad make a breakPoint and check whether your newImage is nil ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.