UIImagePickerController是图片控制器,需要继承UIImagePickerControllerDelegate,UINavigationControllerDelegate代理
点击拍照按钮,模态弹出UIAlertController控制器类,代码如下:
- (void)onCamera
{
//常用控件
//UIAlertView 警告视图 (iOS 8.0以前)
//UIActionSheet (iOS 8.0以前)
//UIAlertController (iOS 8.0以后)
UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//添加第一个Action,从图片库选择照片
[ac addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self loadImagePicker:UIImagePickerControllerSourceTypePhotoLibrary];
}]];
//添加第二个Action,拍照
[ac addAction:[UIAlertAction actionWithTitle:@"照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self loadImagePicker:UIImagePickerControllerSourceTypeCamera];
}]];
//添加第三个Action,取消
[ac addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
}]];
//显示页面
[self presentViewController:ac animated:YES completion:nil];
}
弹出图片控制器
- (void)loadImagePicker:(UIImagePickerControllerSourceType)type
{
//首先,判断soureType 是否可用
if ([UIImagePickerController isSourceTypeAvailable:type]) {
//创建UIImagePickerController对象
UIImagePickerController *pickerContr = [[UIImagePickerController alloc] init];
//设置属性
pickerContr.sourceType = type;
//设置代理
pickerContr.delegate = self;
//显示imagePicker控制器
[self presentViewController:pickerContr animated:YES completion:nil];
}else {
NSLog(@"source type is not available , type = %ld",type);
}
}
两个代理方法
#pragma mark - 代理方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
//返回上一个页面,关闭当前页面
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//info 存储选择的图片
UIImage *img = info[UIImagePickerControllerOriginalImage];
self.iv.image = img;
//关闭页面
[picker dismissViewControllerAnimated:YES completion:nil];
}