0

I have a UICollectionView with 2 sections. I want to select the cell when the user taps on it.

My code runs correctly every time a user taps on the cell, the cell become smaller and a checkmark appears in it ( it's the imageView I add as subview of the cell). The problem is that if I tap a cell on the first section, it selects another cell in the second section. This is weird as I use the indexPath.

This is my code:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    // handle tap events            

    let cell = collectionView.cellForItemAtIndexPath(indexPath)
    let centerCell = cell?.center

    if cell!.frame.size.width == cellWidth {
        cell?.frame.size.width = (cell?.frame.size.width)!/1.12
        cell?.frame.size.height = (cell?.frame.size.height)!/1.12
        cell?.center = centerCell!

        let imageView = UIImageView()
        imageView.image = MaterialIcon.check?.imageWithColor(MaterialColor.white)
        imageView.backgroundColor = MaterialColor.blue.accent2
        imageView.frame = CGRectMake(1, 1, 20, 20)
        imageView.layer.cornerRadius = imageView.frame.height/2
        imageView.clipsToBounds = true
        if indexPath.section == 0 {
            imageView.tag = indexPath.row+4000
        } else {
            imageView.tag = indexPath.row+5000
        }
        print("IMAGEVIEW TAG: ",imageView.tag)
        cell?.addSubview(imageView)                
    }
}
shim
  • 9,289
  • 12
  • 69
  • 108
MarcoCarnevali
  • 671
  • 8
  • 23

1 Answers1

8

Be sure to have the multiple selection property on collectionView set to true in your viewDidLoad() or in storyboard

 collectionView?.allowsMultipleSelection = true 
Andriy
  • 2,767
  • 2
  • 21
  • 29
Cjay
  • 1,093
  • 6
  • 11