话不多说,直接上代码
UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];//这是用来调用相册的button
button.frame = CGRectMake(100, 100, 100, 100);
button.backgroundColor = [UIColor greenColor];
[button addTarget:self action:@selector(buttonAction) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:button];
UIImageView * imageView = [[UIImageView alloc]init];//展示相片的视图
imageView.frame = CGRectMake(100, 220, 200, 200);
imageView.backgroundColor = [UIColor brownColor];
imageView.tag = 101;
[self.view addSubview: imageView];
- (void)buttonAction
{
//创建图片控制器
UIImagePickerController * pc = [[[UIImagePickerController alloc]init] autorelease];
pc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// pc.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//相册的另一种视图形式
// pc.sourceType = UIImagePickerControllerSourceTypeCamera这时候是照相使用的,使用的时候先判断能不能使用相机,模拟机不能拍照,调用相册不会用到
//是否允许被编辑
pc.allowsEditing = YES;
//代理,这时候遵循一下代理
pc.delegate = self;//因为delegete遵守了两个协议,这里只需要一个协议,只遵守了一个
//animated是否要动画
[self presentViewController:pc animated:YES completion:^{
}];
}
UIImagePickerControllerDelegate协议里面的方法,注意先去遵循协议,才会有这个方法的提示
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
//把得到的相册传递为标记的ImageView
UIImageView * img = (UIImageView *)[self.view viewWithTag:101];
img.image = info[UIImagePickerControllerEditedImage];
NSLog(@"%@",info);
//退出
[self dismissViewControllerAnimated:YES completion:^{
} ];
}