相机相册的调用其实很简单,和把大象关进冰箱一样正常的复制以下几步代码就好
1.首先添加代理和需要的全局对象
@interface MineChangesViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>{ UIActionSheet *_sheet_HeadImg;//头像sheet }
2.建立一个UIActionSheet(根据自己需求)让用户选择相机拍照或者调用相册
#pragma mark sheet - (void)headImgBtnDown{ _sheet_HeadImg = [[UIActionSheet alloc] initWithTitle:@"我要~" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil]; [_sheet_HeadImg showInView:self.view]; }
3.复制粘贴UIActionSheet的代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex { if([actionSheet isEqual:_sheet_HeadImg]){ switch (buttonIndex) { case 0: {//相机 UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = self; //设置拍照后的图片可被编辑 picker.allowsEditing = YES; picker.sourceType = sourceType; [self presentModalViewController:picker animated:YES]; }else { NSLog(@"模拟其中无法打开照相机,请在真机中使用"); NSLog(@"%@",[[NSBundle mainBundle] bundleIdentifier]); } break; } case 1: {//相册,直接使用我们的imagepickercontroller去相册里选一张图回来 UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; UIImagePickerController *ff = [[UIImagePickerController alloc] init]; ff.delegate = self; ff.allowsEditing = YES; ff.sourceType = sourceType; ff.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; [self presentViewController:ff animated:YES completion:nil]; break; } default: break; } } }
4.复制黏贴相机的代理方法
#pragma mark - UIImagePickerControllerDelegate 代理方法 // 当得到照片或者视频后,调用该方法 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ UIImage *theImage = nil; // NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType]; // if ([mediaType isEqualToString:( NSString *)kUTTypeImage]){ if ([picker allowsEditing]){ theImage = [info objectForKey:UIImagePickerControllerEditedImage]; } else { theImage = [info objectForKey:UIImagePickerControllerOriginalImage]; } // } [picker dismissViewControllerAnimated:YES completion:^{ //这里写得到照片后的操作(比如替换头像,或者传到服务器的UIImage都是他)--theImage }]; } // 当用户取消时,调用该方法 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{ [picker dismissViewControllerAnimated:YES completion:^{ }]; }
你比你想象的更加强大,如果有写错的地方欢迎留言告诉我哦~
感谢观看,学以致用更感谢!