Oakland510 Oakland510 - 4 months ago 64
Swift Question

Programmatically add class to UIbutton in Swift

I'm new to Swift and am confused as how to programmatically add a custom class to a button. I created a custom class and can add it using the storyboard. It works fine, but how would this be done programmatically?

enter image description here

Can I use the CheckBox class in place of UIButton or would I still need to use UIButton and add the class?

The Class

class CheckBox: UIButton {

//images
let checkedImage = UIImage(named: "checked_checkbox") //as UIImage!
let uncheckedImage = UIImage(named: "unchecked_checkbox") //as UIImage!

//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 {
println("setting to false")
isChecked = false
}else{
println("setting to true")
isChecked = true
}
}
}
}


Adding the class to the view controller

override func viewDidLoad() {
super.viewDidLoad()

let checkBox = CheckBox()

checkBox.backgroundColor = UIColor.blueColor()
self.view.addSubview(checkBox)

checkBox.setTranslatesAutoresizingMaskIntoConstraints(false)


self.view.addConstraint(NSLayoutConstraint(item: checkBox, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 50))
self.view.addConstraint(NSLayoutConstraint(item: checkBox, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 50))


}

Answer

the checkbox does not appear

Could that be because you have forgotten to give your checkbox any size?

Also, I notice you have these images:

let checkedImage = UIImage(named: "checked_checkbox") //as UIImage!
let uncheckedImage = UIImage(named: "unchecked_checkbox") //as UIImage!

But could it be that you have forgotten to put either of those images in the button? I don't see any code that does that.

If I call checkbox.isCheck = true or false the checkbox appears but does not change if clicked

Could that be because you have forgotten to give your checkbox any target-action for its control event? Previously you had this code:

override func awakeFromNib() {
    self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
    self.isChecked = false
}

But now there is no awakeFromNib call - this button does not awake from a nib. The storyboard is the nib. This button is coming from code now.

If you fix that, so that that code is called, then isChecked will be set and the image will appear, won't it?