話不多說,直接上代碼
UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];//這是用來調(diào)用相冊的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
{
//創(chuàng)建圖片控制器
UIImagePickerController * pc = [[[UIImagePickerController alloc]init] autorelease];
pc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// pc.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//相冊的另一種視圖形式
// pc.sourceType = UIImagePickerControllerSourceTypeCamera這時候是照相使用的,使用的時候先判斷能不能使用相機,模擬機不能拍照,調(diào)用相冊不會用到
//是否允許被編輯
pc.allowsEditing = YES;
//代理,這時候遵循一下代理
pc.delegate = self;//因為delegete遵守了兩個協(xié)議,這里只需要一個協(xié)議,只遵守了一個
//animated是否要動畫
[self presentViewController:pc animated:YES completion:^{
}];
}
UIImagePickerControllerDelegate協(xié)議里面的方法,注意先去遵循協(xié)議,才會有這個方法的提示
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
//把得到的相冊傳遞為標(biāo)記的ImageView
UIImageView * img = (UIImageView *)[self.view viewWithTag:101];
img.image = info[UIImagePickerControllerEditedImage];
NSLog(@"%@",info);
//退出
[self dismissViewControllerAnimated:YES completion:^{
} ];
}