The title says it all. Here is my code:
func createCheckBoxButton(xPos: CGFloat, yPos: CGFloat, tag: Int) -> UIButton {
var checkBox = UIButton(frame: CGRect(x: xPos, y: yPos, width: checkBoxSize, height: checkBoxSize))
checkBox.setBackgroundImage(UIImage(named: "checkbox_inactive"), forState: UIControlState.Normal)
checkBox.setBackgroundImage(UIImage(named: "checkbox_pressed"), forState: UIControlState.Highlighted)
checkBox.setBackgroundImage(UIImage(named: "checkbox_active"), forState: UIControlState.Selected)
checkBox.tag = tag
checkBox.contentMode = .ScaleAspectFit
checkBox.addTarget(self, action: "processButton:", forControlEvents: UIControlEvents.TouchUpInside)
return checkBox
}
And there is the called function when my button is pressed:
func processButton(sender: UIButton) {
if (answerViewArray[sender.tag].backgroundColor == UIColor.whiteColor()) {
answerViewArray[sender.tag].backgroundColor = myColor.pinky()
} else {
answerViewArray[sender.tag].backgroundColor = UIColor.whiteColor()
}
let tag = answerButtonsArray[sender.tag]
answer.buttonPressed(tag)
}
When I launch the app, the checkbox_inactive
image is there. When I press and keep it pressed, the checkbox_pressed
image appears. But when I release my click the checkbox_inactive
appears again instead of checkbox_active
.
I also tried with an UIImageView
, which would be the best solution for me actually. I set my checkbox as an UIImageView
and at the top of my general view I put an invisible view so I can click everywhere. But when I press my invisible view, the UIImageView
simply disappears.
Here is the code:
func createCheckBoxButton(xPos: CGFloat, yPos: CGFloat) -> UIImageView {
var checkBox = UIImageView(frame: CGRect(x: xPos, y: yPos, width: checkBoxSize, height: checkBoxSize))
checkBox.image = UIImage(named: "checkbox_inactive")
checkBox.contentMode = .ScaleAspectFit
return checkBox
}
Here is the function called:
func processButton(sender: UIButton) {
if (answerViewArray[sender.tag].backgroundColor == UIColor.whiteColor()) {
answerViewArray[sender.tag].backgroundColor = myColor.pinky()
checkBoxArray[sender.tag].image = UIImage(named: "checkbox-active")
} else {
answerViewArray[sender.tag].backgroundColor = UIColor.whiteColor()
checkBoxArray[sender.tag].image = UIImage(named: "checkbox-inactive")
}
let tag = answerButtonsArray[sender.tag]
answer.buttonPressed(tag)
}
To make appear checkbox_active when you release your button you should make selected=true for the pressed button.
So your function should be like:
func processButton(sender: UIButton) {
// If button not selected
if(sender.selected==false){
sender.selected = true;
}
else{ // If button already selected
sender.selected = false;
}
// Do your other stuff
}