Попробуйте это
Создать переменную в контроллере
let imagePickerController = UIImagePickerController()
Добавить это в viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
imagePickerController.modalPresentationStyle = .popover
}
Вызовите эту функцию из любого места или вы также можете добавить в качестве метода жеста
func addActionSheet() {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let galleryOption = UIAlertAction(title: "Choose Photo", style: .default, handler: { action in
self.imagePickerController.sourceType = .photoLibrary
self.present(self.imagePickerController, animated: true, completion: nil)
})
let cameraOption = UIAlertAction(title: "Take Photo", style: .default, handler: { action in
self.imagePickerController.sourceType = .camera
self.present(self.imagePickerController, animated: true, completion: nil)
})
let deleteOption = UIAlertAction(title: "Delete Photo", style: .default, handler: { action in
self.imageView.image = nil
})
let cancelOption = UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
self.dismiss(animated: true, completion: nil)
})
alertController.addAction(galleryOption)
alertController.addAction(cameraOption)
alertController.addAction(deleteOption)
alertController.addAction(cancelOption)
self.present(alertController, animated: true, completion: nil)
}
Добавить метод делегата UIImagePickerControllerDelegate
или UINavigationControllerDelegate
для получения изображения
extension ControllerName: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
self.imageView.image = image
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}