Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

grandM

macrumors 68000
Original poster
Oct 14, 2013
1,568
329
So I have two checkBoxes. They are outlets. They are called catCheckBox and dogCheckBox. One day there might be added a birdCheckBox. The implementation of checkBox you can find beneath:
Code:
class CheckBox: UIButton {

    // Images

    let checkedImage = UIImage(named: "check")! asUIImage

    let uncheckedImage = UIImage(named: "shapes")! asUIImage

  

    // Bool property

    var isChecked: Bool = false {

        didSet{

            if isChecked == true {

                self.setImage(checkedImage, forState: .Normal)

            } else {

                self.setImage(uncheckedImage, forState: .Normal)

            }

        }

    }

  

    override func awakeFromNib() {

        self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

        self.isChecked = false

    }

  

    func buttonClicked(sender: UIButton) {

        if sender == self {

            if isChecked == true {

                isChecked = false

            } else {

                isChecked = true

            }

        }

    }

}

If I hit dogCheckBox I want to uncheck the catCheckBox and the birdCheckBox. I'm already considering a collectionView but it's not in a collectionView at the moment. Anyhow. I was trying to go
Code:
var dogChecked = self.dogCheckBox.isChecked {
didSet {
self.uncheckOtherCheckBoxes()
}
}
Xcode is throwing me error after error. For instance VC has no member dogCheckBox. Why is that?
 
A button isn't a checkbox. Usually a UISwitch would be used for a checkbox. What you're talking about is similar to a toggle button. Also, the logic for multiple checkboxes is sometimes called a radio group. Anyway, you would usually place the logic for this outside the button or switch. A natural place for this code is in the view controller unless you want to write a radio group controller class that manages your checkboxes.

The logic you show is close to being correct but probably isn't working because you have it inside the button class. In response to a button tap you want to either A) uncheck all the buttons in the group and then check the one that was tapped or B) uncheck the current selection and check the new selection.

To make this most reusable write a separate radio group controller object. In viewDidLoad create an instance and register the checkboxes with it. The checkboxes will have the radio group controller as one target for the button tapped action and the radio group controller will uncheck the other buttons in response. This should be simple to write.
 
  • Like
Reactions: grandM
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.