Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

uicollectionview - Button action inside a collection view cell in swift

In my collection view 6 cells are there. every cell has a button. if i will tap on any of the button, then the image of button will be changed to tick mark image and all other cell button will be changed to untick mark image.Please any one help me. I have added the code and the image here.

In this image a tableview is there and inside the tableview cell collectionview is there.

enter image description here

My code is:-

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InsuranceCollectionViewCell", for: indexPath) as? InsuranceCollectionViewCell else {
            return UICollectionViewCell()
        }
        cell.selectionButton.tag = indexPath.row
        let insuranceTypeAtIndex = insuranceTypeArray[indexPath.row]
        cell.insuranceTypeLabel.text = insuranceTypeAtIndex
        cell.selectionButton.addTarget(self, action: #selector(selectButtonAction(sender:)), for: .touchUpInside)
        return cell
    }


   @objc func selectButtonAction(sender: UIButton){
        let index = IndexPath(row: sender.tag, section: 0)
        let cell = insuranceTypeCollectionView.cellForItem(at: index) as? InsuranceCollectionViewCell
     
        
        if cell?.selectionButton.currentImage == UIImage(named: "untick"){
            cell?.selectionButton.setImage(UIImage(named: "tick"), for: .normal)
            print(cell?.insuranceTypeLabel.text)
        }
        else{
            cell?.selectionButton.setImage(UIImage(named: "untick"), for: .normal)
        }
    }
question from:https://stackoverflow.com/questions/65939782/button-action-inside-a-collection-view-cell-in-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why are you using a button in the collection view. You should use here the delegate method func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)

In this delegate you can toggle the checkmark when clicked by the user.

The collection view cell should then be a label and a view that simulates a checkmark box.

Kind regards, MacUserT


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...