我正在尝试构建一个视图,用户可以在其中选择图像,并在远离视图并再次返回后保留在该视图中。作为一个简单的测试应用程序,我创建了两个视图控制器。第一个视图控制器有一个前进按钮,并使用模态segue转到第二个视图控制器。第二个视图控制器有一个后退按钮(模态segue返回到第一个视图控制器)一个选择按钮和一个图像按钮。到目前为止,我已经配置了选择按钮,使用imagepickercontroller从库中选择一个图像,并显示在按钮上,没有问题。问题是,当我按下后退按钮并再次向前返回到同一屏幕时,图像不会被保留,我必须重新选择它。目的是让用户能够拍摄自己执行动作的图片或视频,然后在该应用程序中选择它并将图片显示在那里以供将来参考。
我的编码如下:
ViewController.h
@interface ViewController : UIViewController
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
IBOutlet UIButton *selectFromPhotoLibraryButton;
IBOutlet UIButton *displayPictureButton;
}
@property (nonatomic, retain) UIButton *selectFromPhotoLibraryButton;
@property (nonatomic, retain) UIButton *displayPictureButton;
- (IBAction)selectPicture;
@end
ViewController.m
@implementation ViewController
@synthesize selectFromPhotoLibraryButton;
@synthesize displayPictureButton;
-(IBAction)selectPicture
{
if([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypePhotoLibrary])
{
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:picker animated:YES];
[picker release];
}
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo: (NSDictionary *)info
{
UIImage *image = [[info objectForKey:UIImagePickerControllerOriginalImage] retain];
[displayPictureButton setImage:image forState:UIControlStateNormal];
[self dismissModalViewControllerAnimated:YES];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *) picker
{
[picker dismissModalViewControllerAnimated:YES];
}
如果您需要任何其他代码(仅限默认应用内容,无需进一步修改),请告诉我。
答案 0 :(得分:0)
关注你的问题
我认为您必须将选定的图像存储在NSUserDefault中作为存档数据或类似的东西。
当你回到第二个视图时,请先在NSUserDefault中检查图像是否已保存。
如果你得到它,那么通过unarchiving将它分配给UIImage对象。
由于我没有实施,所以无法确定。
答案 1 :(得分:0)
我自己设置了类似的东西,我将所选图像立即放在UIImageView中。
首先,将视图控制器设置为UIImagePickerDelegate:
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
然后,无论你想在哪里初始化UIImagePicker,分配,初始化并将其委托设置为self:
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
[imagePicker setDelegate:self];
[self presentViewController:imagePicker animated:YES completion:nil];
然后我让图像选择器将UIImage存储到ImageView中,也存储到NSUserDefaults中。
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo: (NSDictionary *)info {
UIImage *image = [[info objectForKey:UIImagePickerControllerOriginalImage] retain];
[userDefaults setObject:image forKey:@"image"];
[userDefaults synchronize];
[self dismissViewControllerAnimated:YES completion:^{
[self updatePreviewImage:image];
}];
}
- (void) imagePickerControllerDidCancel:(UIImagePickerController *) picker {
[self dismissViewControllerAnimated:YES completion:nil];
}
我希望这适用于您和其他任何查看此帖子的人。