首页 > 解决方案 > UICollectionViewCell 确实选择项目不起作用

问题描述

我对 TableVieCell 中的 collectionView 有疑问。当我点击 collectionCell 时,不会调用 didSelectItemAt。我在 collectionCell 中有一个按钮,所以我尝试禁用用户交互并启用 contentView userInteraction 但它不起作用。

我的表格单元格

红色矩形是tableCell,蓝色矩形是collecionView insede 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()
}

表格单元格

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")
}

}

收集单元

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()
}

}

标签: iosswiftxcode

解决方案


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%


推荐阅读