1

I have a UICollectionViewCell, which has a button as checkbox. Since it is a reusable cell, suppose number of cells rendered are 4. Now, I want to toggle the checkboxes as: if checkbox in one cell is checked, then when I try to tick the checkbox of another reusable cell, then the previous checked cell image should be unchecked automatically, so that I can tick only one checkbox at the time out of all the cells.

Currently, my code is as:

class SelectCollectionCell: UICollectionViewCell {

@IBOutlet weak var teamName: UILabel!
@IBOutlet weak var checkButton: UIButton!
var teamSelected: Bool = false

override func awakeFromNib() {
    super.awakeFromNib()
    checkButton.setImage(#imageLiteral(resourceName: "checked"), for: .selected)
}

func configureCell(_ teams: UserTeamModel) {
    self.teamName.text = teams.name
    self.checkButton.tag = teams.id
}

@IBAction func checkButtonHandler(_ sender: UIButton) {
    sender.isSelected = !sender.isSelected
    if sender.isSelected {
        SelectTeamView.selectedTeamId = self.checkButton.tag
    }
    else {
        SelectTeamView.selectedTeamId = nil
    }
}
}

How can I achieve that? Please help.

  • Please check answer of this question https://stackoverflow.com/questions/39888034/uicollectionview-allow-single-selection-for-specific-cell/39893050#39893050 – Maulik Pandya Jan 26 '18 at 14:04
  • @Maddyヅヅ didnt work either, behaving the same way as its already behaving. i can select multiple checkboxes at a time, which i dont want – Apoorva Verma Jan 26 '18 at 14:43

2 Answers2

0

You can use Notification and Observer. Here the documentation: - https://developer.apple.com/documentation/foundation/nsnotificationcenter

In a nutshell:

  1. when you select a checkbox, you send a notification and than set the observer for that cell
  2. when you deselect a checkbox you remove the observer for that cell

In this way every time a cell receive the notification, you can manage the event and deselect the cell automatic and then stop to listen for new events for that cell.

Fab
  • 816
  • 8
  • 17
-1

Try saving the data with UserDefault with the "teamname" as the key

add this to checkButtonHandler to place the Bool

UserDefaults.standard.set(teamSelected, forKey: teamName)

and in case if you want to get the data from other ViewControllers

UserDefaults.standard.bool(forKey: teamName)
Yuto
  • 658
  • 2
  • 8
  • 20