Fails to load image from UIImagePickerController o

2019-08-08 03:10发布

问题:

I am trying to load a picture selected on UIImagePickerController on the next view controller. i did some search on similar threads and found a few that helped me set it up, but the image does not really get 'transfered' to the next view controller.

this is my code for the didFinishPickingImage and prepareForSegue:

- (void)imagePickerController:(UIImagePickerController *)picker
                              didFinishPickingImage:(UIImage *)image 
                              editingInfo:(NSDictionary *)editingInfo
{
    self.imageChosen = image;
    [picker dismissModalViewControllerAnimated:NO];
    [self performSegueWithIdentifier:@"Edit" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{
    if ([segue.identifier isEqualToString:@"Edit"]){
    EditViewController *editViewController = 
                       (EditViewController *)segue.destinationViewController;
    editViewController.imageView.image = self.imageChosen;
}

I am getting the segue running to the EditViewController, but the imageView there doesnt load the picture. I guess the assignment is wrong somehow but I fail to see how.

回答1:

When you try to set image to EditViewController UIImageView it doesn't not exist because EditViewController not loaded yet. Instead of setting image to UIImageView directly create an instance variable in EditViewController that will hold image. And than assign this image to UIImageView in viewDidLoad:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{
    if ([segue.identifier isEqualToString:@"Edit"]){
    EditViewController *editViewController = 
                   (EditViewController *)segue.destinationViewController;
    editViewController.image = self.imageChosen;
}

//EditViewController.h
...
@property (nonatomic, strong) UIImage *image;
...

//EditViewController.m
- (void)viewDidLoad {
    ...
    self.imageView.image = self.image;
    ...
}