Search code examples
swiftxcodeswiftuiuibuttonuiimagepickercontroller

How do I set an image in a cell class from a ImagePicker Controller


I'm trying to change the image of a button to an image that the user picked in the imagePicker, but I am presenting the image picker in the ViewController class and the button is in the cell class.

I'm not sure how to set it from a different class. Here is the code I have for presenting the image picker and the way the button is created:

Here is my profileVC class:

class UserProfileVC: UICollectionViewController, UICollectionViewDelegateFlowLayout, UserProfileHeaderDelegate {

    func handleEditBannerTapped(for header: ProfileHeader) {
        let imagePicker = UIImagePickerController()
        imagePicker.allowsEditing = true
        present(imagePicker, animated: true, completion: nil)
    }

}

The above code is working fine and is presenting all pictures on the device for the user to choose.

Here is my ProfileHeader Cell class

class ProfileHeader: UICollectionViewCell, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

   lazy var profileBanner: UIButton = {
       let button = UIButton()
       button.clipsToBounds = true
      
       let imageTapped = UITapGestureRecognizer(target: self, action: #selector(handleBannerTapped))
       imageTapped.numberOfTapsRequired = 1
       button.isUserInteractionEnabled = true
       button.addGestureRecognizer(imageTapped)
       return button
   }()

    @objc func handleBannerTapped() {
        delegate?.handleEditBannerTapped(for: self)
    }
}

How do I set the image that the user picks to the profileBanner Button from the UserProfileVC class?


Solution

  • I'm assuming UserProfileVC is the main class, which contains a collection view, and ProfileHeader is a cell inside that collection view? You need to know the IndexPath of the cell, then do:

    if let cell = collectionView.cellForItem(at: indexPath) as? ProfileHeader {
         cell.profileBanner.setImage(imageThatYouWant, for: .normal)
    }