Search code examples
iosswiftuiviewuiviewcontrolleruiimagepickercontroller

Swift - access UIImagePickerController from modal view


Is there a way to present an UIImagePickerController from inside a modal view?

In my case I have a class called MakeWishView which is a UIView and the user should be able to pick an image if he taps on a button inside the MakeWishView. My problem right now is that I can not call present because MakeWishView is not a ViewController but a UIView.

This is what I would like to call:

@objc private func wishImageButtonTapped(){
    showImagePickerController()
    print("wishImageButtonTapped")
}

// image picker
extension MakeWishView: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @objc func showImagePickerController(){
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        present(imagePickerController, animated: true, completion: nil) // -> error
    }
}

Solution

  • Add a delegate to the presenting vc like

     class MakeWishView:UIView {
        weak var delegate:VCName?
    

    or

     let root = (UIApplication.shared.delegate as! AppDelegate).window!.rootViewController
     root.present(imagePickerController, animated: true, completion: nil)