UICollectionViewCell did select item not working

Viewed 2398

I have an issue with a collectionView inside a TableVieCell. When i tap on a collectionCell, didSelectItemAt doesn´t get called. I have a button in the collectionCell so i tried to disable the user interaction and enable the contentView userInteraction but it didn't work.

My Table cell

The red rectangle is the tableCell and the blue rectangle is the collecionView insede the table view cell

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


            if let cell = tableView.dequeueReusableCell(withIdentifier: "MedCellWithCollection") as? MedCellWithCollection{
                
                let backgroundView              =  UIView()
                backgroundView.backgroundColor  =  UIColor.white.withAlphaComponent(0.0)
                cell.selectedBackgroundView     =  backgroundView
                                
                cell.setMedName(name: self.medCatalog[indexPath.row].nombre, uso: self.medCatalog[indexPath.row].uso , array: self.medCatalog[indexPath.row].enfermedades[0].aplicaciones  , index: indexPath.row)
    
                cell.layoutIfNeeded()
                cell.layoutSubviews()
                cell.setNeedsUpdateConstraints()
                cell.updateConstraintsIfNeeded()
                
               
                return cell
            }
        
    }
   
    return UITableViewCell()
}

The tableCell

class MedCellWithCollection: UITableViewCell {

//Outlets
@IBOutlet weak var medText: UILabel!
@IBOutlet weak var uso: UILabel!
@IBOutlet weak var arrowIcon: UIImageView!

@IBOutlet weak var CollectionView: UICollectionView!

//Variables
var dosesType:[Aplicacion]?


override func awakeFromNib() {
    super.awakeFromNib()
    self.collectionViewSetUp()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}


func setMedName(name: String, uso: String, array: [Aplicacion], index: Int){
    self.medText.text = name
    self.uso.text     = uso
    
    self.dosesType = array
    
    self.CollectionView.reloadData()
}


} 
extension MedCellWithCollection: UICollectionViewDataSource, UICollectionViewDelegate{

func collectionViewSetUp(){
    self.CollectionView.delegate    =  self
    self.CollectionView.dataSource  =  self
}


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.dosesType?.count ?? 0
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "doseColletion", for: indexPath as IndexPath) as? DoseCollection {
        
            
        cell.setButtonConfig(doseType: self.dosesType![indexPath.row].metodo , index: indexPath.row)
            
            return cell
    }
    
    return UICollectionViewCell()
    
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("tapped")
}

}

CollectionCell

import UIKit

class DoseCollection: UICollectionViewCell {

//Outlets
@IBOutlet weak var Button: Button!

//Variables
let constants = Constants()

func setButtonConfig(doseType: String, index: Int){
    
    self.Button.titleLabel?.text = doseType
    
    self.Button.backgroundColor = constants.COLOR_ARRAY[index]
    
    
}


override func layoutSubviews() {
    super.layoutSubviews()
}

override func layoutIfNeeded() {
    super.layoutIfNeeded()
}

}
2 Answers

Potential Solutions:

1) Should be Single Selection for tableView selection property, programmatically it can be done by tableView.allowsSelection = true

table view Selection property

2) The class is not the UITableViewDelegate for that table view, though UITableViewController is supposed to set that automatically.

tableView?.delegate = self

3) If the problem arise with UITapGestureRecognizer:

let tap = UITapGestureRecognizer(target: self, action:Selector("dismissKeyboard"))
view.addGestureRecognizer(tap)
tap.cancelsTouchesInView = false

BOL :)

In my case, I want to change the background of the button in other words the background of the cell in the collection view:

class CustomCVCell: UICollectionViewCell {

override var isSelected: Bool {
        didSet {
            grayBackgroundViewWithImage.image =
                isSelected ? UIImage(named: "") : UIImage()
        }
    }

In the main class where the collection view is stored create this variable:

class CustomViewController: UIViewController {

///save the indexPath of last selected cell
private var lastSelectedIndexPath: IndexPath? }

In viewDidLoad() set this value to false:

customCollectionView.allowsMultipleSelection = false

Further code in data source. In my case, the first cell should be is selected:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CustomCVCell.cellID(),
                                                  for: indexPath) as! CustomCVCell
    
    if indexPath.row == 0 {
        lastSelectedIndexPath = indexPath
        cell.isSelected = true
    }
    
    //update last select state from lastSelectedIndexPath
    cell.isSelected = (lastSelectedIndexPath == indexPath)
    
    return cell
}

Further code in the delegate:

///UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    guard lastSelectedIndexPath != indexPath else { return }

         if let index = lastSelectedIndexPath {
            let cell = collectionView.cellForItem(at: index) as! CustomCVCell
            cell.isSelected = false
          }

          let cell = collectionView.cellForItem(at: indexPath) as! CustomCVCell
          cell.isSelected = true
    lastSelectedIndexPath = indexPath
}

First Button isSelected by Default tap the next! more)) And finally, All works 100%

Related