如何在快速的同时在UIImagePickerController相机和照片库

我使用UIImagePickerController通过iPhone的相机拍照。

我想展示两个“拍照”和“select一张照片”。

我的代码

imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .Camera //imagePicker.sourceType = .PhotoLibrary presentViewController(imagePicker, animated: true, completion: nil) 

我试图使用imagePicker.sourceType = .CameraimagePicker.sourceType = .PhotoLibrary一起做到这一点,但它不工作…

谢谢

导入UIImagePickerControllerDelegate并创build一个variables来分配UIImagePickerController var imagePicker = UIImagePickerController()并设置imagePicker.delegate = self

创build一个操作表来显示“相机”和“照片库”的选项。

在你的button点击动作:

 @IBAction func buttonOnClick(_ sender: UIButton) { self.btnEdit.setTitleColor(UIColor.white, for: .normal) self.btnEdit.isUserInteractionEnabled = true let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in self.openCamera() })) alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in self.openGallary() })) alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil)) /*If you want work actionsheet on ipad then you have to use popoverPresentationController to present the actionsheet, otherwise app will crash on iPad */ switch UIDevice.current.userInterfaceIdiom { case .pad: alert.popoverPresentationController?.sourceView = sender alert.popoverPresentationController?.sourceRect = sender.bounds alert.popoverPresentationController?.permittedArrowDirections = .up default: break } self.present(alert, animated: true, completion: nil) } func openCamera() { if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) { imagePicker.sourceType = UIImagePickerControllerSourceType.camera imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } func openGallary() { imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } 

从这里下载示例项目。