如何在调用其他操作时保持用户选择的图像显示

时间:2013-12-28 15:36:23

标签: ios objective-c uiimageview uiimage uiimagepickercontroller

好的,这里有完整的菜鸟,但基本上这是我的问题。我有一个按钮,点击后打开照片库,用户选择照片后,它会显示在UIImageView中。

//select photo

- (IBAction)selectPhoto:(UIButton *)sender {

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

[self presentViewController:picker animated:YES completion:NULL];


}

//delegate methods

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    {
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    [self dismissViewControllerAnimated:NO completion:NO];
    // Handle a movie capture
        if (CFStringCompare ((__bridge_retained CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) {
        NSString *moviePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(moviePath)) {
            UISaveVideoAtPathToSavedPhotosAlbum(moviePath, self, nil, nil);
        }
    }
}

//photo
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;
}



- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

[picker dismissViewControllerAnimated:YES completion:NULL];

 }

然后我还有一个打开照片库并拍摄视频或拍摄视频的按钮,然后显示。然而,如果选择了一个图像,然后单击另一个按钮,则选择视频和原始图像视图控制器显示UIImage现在是空白的。但令我困惑的是,如果首先选择视频,这不会发生,感谢您提供的任何帮助,只要询问您是否需要用于选择视频的代码,感谢。

1 个答案:

答案 0 :(得分:0)

您的委托方法imagePickerController:didFinishPickingMediaWithInfo:可能在您选择照片时调用一次,在您选择视频时调用一次。当您选择照片时,info[UIImagePickerControllerEditedImage]会包含您选择的照片,但在您选择视频时,可能会nil。如果您使用视频或照片进行操作并调用此代码,则应检查此方法:

UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;

仅在您处理照片时(否则self.imageView.image将设为nil

编辑:解决方案

- (void)imagePickerController:(UIIMagePickerController *)controller   didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if ([info objectForKey:@"UIImagePickerControllerMediaType"] == kUTTypeImage) {
       //photo related code

    } else {
       //video related code

    }
}

检查doc for what's get returned in the info dictionary。希望你明白