调用系统相册选择一张图片并显示出来,系统相册只能单选。
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UIImageView *Image;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//创建按钮
[self creatControl];
}
- (void)creatControl {
//相册按钮
scanBtn = [UIButton buttonWithType:UIButtonTypeSystem];
scanBtn.frame = CGRectMake(100, 100, 100, 44);
[scanBtn setTitle:@"打开相册" forState:UIControlStateNormal];
[scanBtn addTarget:self action:@selector(scanBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:scanBtn];
//显示的相册图片
self.Image = [[UIImageView alloc]initWithFrame:CGRectMake(100, 150, 200, 300)];
[self.view addSubview:self.Image];
}
-(void)scanBtnOnClick {
//打开之前一定要判断设备是否可用
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIImagePickerController *photos = [[UIImagePickerController alloc]init];
//数据源
photos.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//照片可编辑,在相册选中图片后会经过一个编辑框
photos.allowsEditing =YES;
//代理
photos.delegate = self;
//显示系统相册
[self presentViewController:photos animated:YES completion:nil];
}
else {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
message:@"当前设备不支持访问相册"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * _Nonnull action) {
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * _Nonnull action) {
}];
[alert addAction:sureAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
}
}
#pragma mark - UIImagePickerControllerDelegate代理
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
//获取选中的原始图片
UIImage *img = info[UIImagePickerControllerOriginalImage];
//获取编辑后的图片
UIImage *img1 = info[UIImagePickerControllerEditedImage];
//显示或可以做其他任何操作
self.Image.image = img;
//一定要关闭相册界面
[picker dismissViewControllerAnimated:YES completion:nil];
}
@end