yufan
yufan

Reputation: 23

Swift collection view selections

I got a collection view of photos, how can I limit the number of photos that users selected. e.g. The users can select up to 3 photos in the collection view

Upvotes: 0

Views: 66

Answers (2)

fazeel ahamed
fazeel ahamed

Reputation: 84

You can add the selected items into a new array and check for the count of the array to not exceed 3 items.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
     if alreadyAddedItemArray.count == 3 {
        // replace the selected indexPath item with last added item
        // or any logic you prefer
     }
     else {
       // append new item to alreadyAddedItemArray.
     }
}


Upvotes: 0

Enea Dume
Enea Dume

Reputation: 3232

This woked for me. I have build two methods one for handleMultipleCellSelection to check the max selected number of items and one other for handleCellSelection.

This method handleMultipleCellSelection is called in didSelectItemAt of UICollectionViewDelegate

var selectedServicesId = NSMutableArray()

  func handleMultipleCellSelection(_ cell: UICollectionViewCell, indexPath: IndexPath){
        if self.selectedServicesId.count < 3 {
            self.handleCellSelection(cell, indexPath: indexPath)
        }else{
            if  self.selectedServicesId.contains(servicesData!.data[indexPath.row].id){
                handleCellSelection(cell, indexPath: indexPath)
            }else{

                let alert = UIAlertController(title: "Attention", message: "You can not select more than three items", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "Ok", style: .destructive, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }
        }
    }

func handleCellSelection(_ cell: UICollectionViewCell, indexPath: IndexPath){
    if cell.backgroundColor == UIColor.white{

        cell.backgroundColor = UIColor(hexString: "#FFB74D")
        self.selectedServicesId.add(servicesData!.data[indexPath.row].id)
        self.searchView.alpha = 1
    }else{
        cell.backgroundColor = UIColor.white
        self.selectedServicesId.remove(servicesData!.data[indexPath.row].id)
        if selectedServicesId.count == 0{
            self.searchView.alpha = 0
        }
    }
}
}

and in your didSelectItemAt:

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell : UICollectionViewCell = collectionView.cellForItem(at: indexPath) as! CategoryCollectionViewCell
        handleMultipleCellSelection(cell, indexPath: indexPath)
    }

Upvotes: 1

Related Questions