调取相机、相册

2016-06-29  本文已影响78人  fwlong

点击图片调取相机或相册

//遵循协议(调取相册、相机使用)
<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
//给头像开启用户交互
 self.avatarImage.userInteractionEnabled = YES;
//设置手势识别
    UITapGestureRecognizer * recognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addDevies)];
    [self.avatarImage addGestureRecognizer:recognize];

//图片点击事件
- (void)addDevies
{
    //创建UIAlertController是为了让用户去选择照片来源,拍照或者相册.
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:0];
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    //相册
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册选取" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }];
    
    //相机
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }];

    //取消
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action)
                                   {
                                       //这里可以不写代码
                                   }];
    [self presentViewController:alertController animated:YES completion:nil];
    
    //用来判断来源 Xcode中的模拟器是没有拍摄功能的,当用模拟器的时候我们不需要把拍照功能加速
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        
    {
        
        [alertController addAction:albumAction];
        [alertController addAction:cancelAction];
        [alertController addAction:photoAction];
        
    }
    
    else
    {
        [alertController addAction:albumAction];
        [alertController addAction:cancelAction];

        [alertController addAction:photoAction];
    }
    
}

选取完照片后要执行的代理方法

上一篇下一篇

猜你喜欢

热点阅读