1

I am trying to implement a checkbox in Swift. I used the answer of an other post to get started. First I created a button in the storyboard and gave it the class checkbox. After that I, created the class checkbox. It is currently looking like that. I had do make some adjustments from the other post, because he was using a different version of swift.

    class checkbox: UIButton {

    //Images
   let checkedImage = UIImage(named: "selected")! as UIImage
   let uncheckedImage = UIImage(named: "rectangle")! as UIImage

    // Bool property
    var isChecked: Bool = false {
        didSet{
            if isChecked == true {
                self.setImage(checkedImage, for: .normal)
            } else {
                self.setImage(uncheckedImage, for: .normal)
            }
        }
    }

    func buttonClicked(sender: UIButton) {
        if (sender == self) {
            if self.isChecked == true
            {
                self.isChecked = false
            }
            else
            {
                self.isChecked = true
            }
        }
    }


    override func awakeFromNib() {
        self.addTarget(self, action: Selector(("buttonClicked:")),for:UIControlEvents.touchUpInside)
        self.isChecked = false
    }

  }

But now, I always get the following error in the AppDelegate, when I click the checkbox.

terminating with uncaught exception of type NSException
Community
  • 1
  • 1
fabioha
  • 11
  • 1
  • 2

3 Answers3

3

try this -

class CheckBoxButton: UIButton {

override func awakeFromNib() {
    self.setImage(UIImage(named:"selected"), for: .selected)
    self.setImage(UIImage(named:"rectangle"), for: .normal)
    self.addTarget(self, action: #selector(CheckBoxButton.buttonClicked(_:)), for: .touchUpInside)
}

func buttonClicked(_ sender: UIButton) {
    self.isSelected = !self.isSelected
 }

}
Prema Janoti
  • 836
  • 5
  • 18
1

I also recently had to make a checkbox and I used a cocoapod for that, instead of making my own. It lets you choose everything including colors, animations, shape and size! Maybe that helps:

BEM CHECKBOX

It really only takes 5 min to install and have it working on your app.

Florensvb
  • 209
  • 1
  • 10
0

Safest way to make check box:

Add a UIButton to ViewController

Add two images to Project: 1.checked.png, 2.un-checked.png

Set checked or un-checked image as button background or button image

Set button text to ""

believe me, that libraries will make you confused.

Grimxn
  • 22,115
  • 10
  • 72
  • 85
Vahid
  • 3,352
  • 2
  • 34
  • 42