简体   繁体   中英

How to pass UI image from one view controller to another?

I need to pass a image from one view controller to another I had user NSuserdefault to declare the image variable as global but it shows this error app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object

 func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
self.dismissViewControllerAnimated(true, completion: { () -> Void in
})  
imageview.image = image
NSUserDefaults.standardUserDefaults().setObject(image, forKey:"image")
NSUserDefaults.standardUserDefaults().synchronize()
}

What do you means? Pass a UIImage's variables to another viewController? The information you provide is too little.

Maybe you want to look this link Using Delegation to Communicate With Other View Controllers .

只需创建一个NSString * imageName属性,然后在推入/展示一个视图控制器之前对其进行设置,就可以在其他视图控制器中读取该属性来创建UIImage。

You can't save image directly into the UserDefaults, You can compress image to png/jpeg data,and you can save the data into the userDefault. using method

NSData *UIImagePNGRepresentation(UIImage *image);

and

if imageData {
    NSUserDefaults.standardUserDefaults().setObject(imageData, forKey:"image")
    NSUserDefaults.standardUserDefaults().synchronize()
}

when you read the userDefaults, you can read data firstly, then convert data to image using method

UIImage-imageWithData: or swift style UIImage(data:)

generally, we don't do like above, we save image to file, and save the file's path into the userDefault

To store the image with NSUSerdefaults:

var testimage = UIImage(named: "testimage.png");
NSUserDefaults.standardUserDefaults().setObject(UIImagePNGRepresentation(testimage), forKey:"image")
}

To retrieve it in another class:

var imagedata: NSData = NSUserDefaults.standardUserDefaults().dataForKey("image")!
        imageview.image = UIImage (data: imagedata)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM