iOS相机相册调用 — UIImagePickerController

时间:2025-01-29 22:28:39
  • - (IBAction)chooseImage:(id)sender {
  • // 创建UIImagePickerController实例
  • UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
  • // 设置代理
  • imagePickerController.delegate = self;
  • // 是否允许编辑(默认为NO)
  • imagePickerController.allowsEditing = YES;
  • // 创建一个警告控制器
  • UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选取图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  • // 设置警告响应事件
  • UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  • // 设置照片来源为相机
  • imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
  • // 设置进入相机时使用前置或后置摄像头
  • imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
  • // 展示选取照片控制器
  • [self presentViewController:imagePickerController animated:YES completion:^{}];
  • }];
  • UIAlertAction *photosAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  • imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  • [self presentViewController:imagePickerController animated:YES completion:^{}];
  • }];
  • UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  • }];
  • // 判断是否支持相机
  • if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
  • {
  • // 添加警告按钮
  • [alert addAction:cameraAction];
  • }
  • [alert addAction:photosAction];
  • [alert addAction:cancelAction];
  • // 展示警告控制器
  • [self presentViewController:alert animated:YES completion:nil];
  • }