Search code examples
swiftdelegatesuiimagepickercontrolleruicollectionviewcell

present UIImagePickerController from collectionViewCell class


I am having a little trouble presenting the UIImagePicker from a collectionViewCell. I know collectionViewCells do not act as the picker delegate by default so I did try to call a method from the UIViewController class operating the cell holding the imageView tapped. There are no errors showing in my console, but when I run the app and try to present the UIImagePickerController nothing happens and I receive the "Warning: Attempt to present on whose view is not in the window hierarchy!". I would like to present the UIImagePickerController when user taps on the profileImageView. Thanks in advance for help!

// LoginCell class holding the imageView to call the UIImagePickerController method from LoginController class

       lazy var profileImageView: UIImageView = {
            let imageView = UIImageView()
         imageView.addGestureRecognizer(UITapGestureRecognizer(target:self, action: #selector(handleSelectProfileImage)))
            imageView.isUserInteractionEnabled = true
            return imageView
        }() 

        var loginController: LoginController?

        func handleSelectProfileImage() {
        let loginController = LoginController()
        loginController.showImagePicker(sendingVC: loginController)
    }

// LoginController class as UIImagePickerController delegate

    func showImagePicker(sendingVC: LoginController) {
        let picker = UIImagePickerController()

        picker.delegate = self
        picker.allowsEditing = true

        present(picker, animated: true, completion: nil)

    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let loginCell = collectionView.dequeueReusableCell(withReuseIdentifier: loginCellId, for: indexPath) as! LoginCell
            loginCell.delegate = self
            return loginCell
 }

Solution

  • try this, in your cell:

    func handleSelectProfileImage() {
    
        guard let loginController = delegate as? LoginViewController else {
            return
        }
    
        loginController.showImagePicker()
    }
    

    in your LoginController

    func showImagePicker() {
    
        let picker = UIImagePickerController()
    
        picker.delegate = self
        picker.allowsEditing = true
    
        present(picker, animated: true, completion: nil)
    }