Welcome to OGeek Q&A 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...