Search code examples
iosswiftuicollectionviewphphotolibrary

How do I mark an image as Favorite in my app


I have an array of images and I have three buttons ( Save, Favorite, Share) each image in a collectionviewcell. How do I mark an image as my favorite image? And I would like to display the marked images in a folder inside my app. Thank you!

import Photos 

    @objc func favouriteImage(sender: UIButton) {
            for index in 0..<images.count {
                if sender.tag == index {

                    PHPhotoLibrary.shared().performChanges({
                        let request = PHAssetChangeRequest(forAsset: )
                        request.favorite = true
                    }, completionHandler: { success, error in

                    })


Solution

  • I hope you are using a custom cell for displaying the images and these 3 buttons in the cell. For marking the image as favourite, best way is to use delegation between cell and collection view.

    Following code will go in your custom cell, e.g. ImageCollectionViewCell

    protocol ImageCollectionViewCellProtocol {
     func didSelect(cell: ImageCollectionViewCell)
    }
    
    class ImageCollectionViewCell: UICollectionViewCell {
    
    @IBOutlet weak var favouriteButton: UIButton!
    
    override func awakeFromNib() {
        super.awakeFromNib()        
        let image = UIImage(named: "favourite1.png")
        let imageFilled = UIImage(named: "favourite2.png")
        favouriteButton.setImage(image, for: .normal)
        favouriteButton.setImage(imageFilled, for: .selected)
    }
    
    // The IBAction for Favourite button
    @IBAction func didTapMakeFavourite(_ sender: Any) {
        guard let cell = (sender as AnyObject).superview?.superview as? ImageCollectionViewCell else {
            return // or fatalError() or whatever
        }
    
        self.delegate.didSelect(cell: cell)
        favouriteButton.isSelected.toggle()
    }
    }
    

    Following code will go in your view controller having collectionView implementation, e.g. ImagesCollectionViewController

    extension ImagesCollectionViewController: UICollectionViewDataSource {
                func collectionView(_ collectionView: UICollectionView, 
          cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                 ... 
                    cell.delegate = self
                 ...
                }
    
        }
    
    extension ImagesCollectionViewController: ImageCollectionViewCellProtocol {
            func didSelect(cell: ImageCollectionViewCell) {
                let indexPath = imagesCollectionView.indexPath(for: cell)
                // do whatever you want with this indexPath's cell 
            }
    
    }