Home > Enterprise >  Radio Button Not Working In ColectionView Cell , If I select One Button another Buttons aren't
Radio Button Not Working In ColectionView Cell , If I select One Button another Buttons aren't

Time:11-13

enter image description hereThis Is My Struct For Image and is Image selected Or Not.

struct TeamSelected {
var logoImage: String
var isImageSelected: Bool }

This is variable for checking selection

var selection = Set<Int>()

my cell for row at indexpath method...

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let teamSelection : TeamSelectionCollectionViewCell = self.teamCollectionView.dequeueReusableCell(withReuseIdentifier: "teamCell", for: indexPath) as! TeamSelectionCollectionViewCell
    let index = indexPath.row
    teamSelection.logoImage.image = UIImage(named: teamSelectionList[index].logoImage)
    let isImageSelected = selection.contains(index)
    teamSelection.logoButton.isSelected = isImageSelected
    teamSelection.logoButton.setImage(
        UIImage(named: isImageSelected ? "ic_radio_selected" : "ic_radio_normal"),
        for: UIControl.State.normal
    )

    teamSelection.logoButton.tag = indexPath.row
    teamSelection.logoButton.addTarget(self, action: #selector(logoButtonTapped), for: .touchUpInside)
    teamSelection.seperatorView.isHidden = indexPath.row == 2 || indexPath.row == self.teamSelectionList.count - 1 ? true : false
    return teamSelection

}

this is button Target function...

  @objc func logoButtonTapped(sender: UIButton){
    let index = sender.tag
    if (selection.contains(index)){
        selection.remove(index)
    } else {
        selection.insert(index)
    }
    self.teamCollectionView.reloadData()
}[![Here's My simulator Image, As You Can See if select A button another button is not Deselcting.][1]][1]

CodePudding user response:

If you want to only one can be selected , you could basically do this :

@objc func logoButtonTapped(sender: UIButton){
    let index = sender.tag
    selection.removeAll()
    selection.append(index)
    self.teamCollectionView.reloadData()
}

This condition (selection.contains(index)) only works when index is a part of selection array so when you add new one , old one won't gonna remove

  • Related