我一直试图解决这个问题。我有一个应用程序,用户选择一个图像,而不是选定的图像保存到磁盘,然后加载到UIImageView,但无论我尝试什么,这都不起作用。我做了一个小应用程序只是为了测试它,它也不起作用。 imageView保持空白。这是我的代码:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)button:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.allowsEditing = NO;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *selectedImage = info[UIImagePickerControllerOriginalImage];
[self saveImage:selectedImage];
self.imageView.image = [self loadImage];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)saveImage: (UIImage*)image
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
@"image.png" ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
@"image.png" ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
@end
我做错了什么?
答案 0 :(得分:0)
您只需要添加UIImagePickerController
的委托,以便以下代码解决您的问题。
- (IBAction)button:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.allowsEditing = NO;
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:nil];
}
现在,在.h文件中使用以下代码。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property(nonatomic,weak)IBOutlet UIImageView *imageView;
@end