Passing Image to another View Controller (Swift)
In prepare(for:)
you can't access the @IBOutlet
s of the destination view controller because they haven't been set up yet. You should assign the image to a property of the destination view controller, and then move it into place in viewDidLoad()
:
In source view controller:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toBrowsePage" {
let dvc = segue.destination as! ListPage
dvc.newImage = postingImage.image
}
}
In destination view controller:
class ListPage: UIViewController {
@IBOutlet weak var browsingImage: UIImageView!
var newImage: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
browsingImage.image = newImage
}
}
From your description,browsingImage
is in destination viewController,so
in this line
itemToAdd.postingImage.image = browsingImage.image
You pass the destination imageview to source imageview
IBOutlets are not accessible in your current view controller. The outlets are not yet initialized since the your second view is not yet loaded.
Instead you can create a UIImage variable in your second viewController and assign the value to it in the prepareForSegue.
And in your second viewController's viewDidLoad method assign that value to your ImageView outlet.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toBrowsePage" {
let destination = segue.destinationViewController as! ListPage
destination.receivedImage = postingImage.image
}
}
In your next viewController declare a variable called
@IBOutlet weak var postingImage: UIImageView!
var receivedImage : UIImage?
In the viewDidLoad method
postingImage.image = receivedImage