我想将相机拍摄的照片显示到另一个 UIViewController 中。我尝试了这个代码片段,但我认为我做错了,因为照片没有显示在第二个视图中:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
imageToSave = (editedImage!=nil ? editedImage : originalImage);
// Check if the image was captured from the camera
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
// Save the image to the camera roll
UIImageWriteToSavedPhotosAlbum(imageToSave, nil, nil, nil);
}
NSString *docspath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filepathJPG = [docspath stringByAppendingPathComponent:@"imagefile.jpg"];
NSData *data = UIImageJPEGRepresentation(imageToSave, 0.8);
BOOL result = [data writeToFile:filepathJPG atomically:YES];
NSLog(@"Saved to %@? %@", filepathJPG, (result? @"YES": @"NO") );
[picker dismissViewControllerAnimated:YES completion:nil];
mainViewController *main = [[mainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
main.myImag.image = imageToSave;
}
更新:
我更改为使用情节提要作为第二个视图:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([[segue identifier] isEqualToString:@"idmain"]){
mainViewController *main = (mainViewController *)[segue destinationViewController];
main.myImag.image = imageToSave;
}
}
在 mainViewController 中:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSString *docspath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filepathJPG = [docspath stringByAppendingPathComponent:@"imagefile.jpg"];
UIImage *img = [UIImage imageWithContentsOfFile: filepathJPG];
if (img != nil) {
// assign the image to the imageview,
myImag.image = img;
}
else {
NSLog(@"Image hasn't been created");
}
}
但是当我按下选择第二个视图控制器时没有出现。