Makaille Makaille - 7 months ago 38
Swift Question

pass UIImage with a segue

I want to pass an UIImage between two view with a segue. The problem is that my UIImage appear white in the second view controller.

The segue :

var screenShot = UIImage()

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "screenshotEmbed") {
let svc = segue.destinationViewController as! screenshotViewController
svc.toPass = self.screenshot
}


The secondViewController :

class screenshotViewController: UIViewController {

@IBOutlet var screenshotView: UIImageView!
var toPass = UIImage()

override func viewDidLoad() {
super.viewDidLoad()
self.screenshotView.image = self.toPass
}


}

My UIImage is just a screenshot, here the function :

func captureScreen() -> UIImage {
var window: UIWindow? = UIApplication.sharedApplication().keyWindow
window = UIApplication.sharedApplication().windows[0]
UIGraphicsBeginImageContextWithOptions(window!.frame.size, window!.opaque, 0.0)
window!.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image;
}


EDIT. Screenshot storage on a button :

@IBAction func photoAction(sender: AnyObject) {
self.screenShot = captureScreen()
}


I've tried lot of thing but still blank (not empty cause the memory adress is good).

Answer

Not sure if your screenshotImage object has Image or not.

I tried below code and it's working fine.

import UIKit

class ViewController: UIViewController {

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "screenshotEmbed") {
            let svc = segue.destinationViewController as! ScreenshotViewController
            svc.toPass = captureScreen()
        }
    }

    func captureScreen() -> UIImage {
        var window: UIWindow? = UIApplication.sharedApplication().keyWindow
        window = UIApplication.sharedApplication().windows[0]
        UIGraphicsBeginImageContextWithOptions(window!.frame.size, window!.opaque, 0.0)
        window!.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image;
    }

}

Result with this code:

enter image description here

Project Sample for more Info.