Search code examples
swift3

swift 3 - collection view didSelectItemAt indexPath for checkbox


I'm generally new to Swift. I have two images, which I want them act like checkbox, first image is unchecked box, second image is checked box, by using didSelectItemAt indexPath: in collection View, how am I gonna shift between two images when user tapped on that collectionviewcell. I'm kinda confused. Heres my code:

var buttonCounter = 0 
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return faultyType.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "faulty_type_cell", for: indexPath) as! FaultyTypeCollectionViewCell
    cell.faultyTypeLabel.text = faultyType[indexPath.row]
    if buttonCounter == 0{
    cell.checkboxImage.image = UIImage(named: "Checkboxunpicked")
    }
    else if buttonCounter == 1{
    cell.checkboxImage.image = UIImage(named: "Checkboxpicked")
    }
    else if buttonCounter == 2{
    cell.checkboxImage.image = UIImage(named: "Checkboxpicked")
    }
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
   if indexPath.row == 1{
   buttonCounter = 1
   } 
   if indexPath.row == 2{
   buttonCounter = 2
   }
}

Solution

  • I've found a good solution after searching over the net. Heres my solution in which I refer to : [link]How to access buttons in a UICollectionView from a target function set (Swift 3) Happy coding hunting.

    var BoxOn = UIImage(named: "Checkboxpicked")
    var BoxOff = UIImage(named: "Checkboxunpicked")
    var buttonCounter = [Int]()
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "faulty_type_cell", for: indexPath) as! FaultyTypeCollectionViewCell
        cell.faultyTypeLabel.text = faultyType[indexPath.row]
        cell.checkboxImage.image = BoxOff
        if buttonCounter.contains(indexPath.row){
            cell.checkboxImage.image = BoxOn
    
        }
        else{
            cell.checkboxImage.image = BoxOff
    
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if buttonCounter.contains(indexPath.row){
            let index = buttonCounter.index(of: indexPath.row)
            buttonCounter.remove(at: index!)
            collectionView.reloadItems(at: [indexPath])
        }
        else{
            buttonCounter.append(indexPath.row)
            collectionView.reloadItems(at: [indexPath])
        }
        print(buttonCounter)
    }