Omar Omar - 1 year ago 77
iOS Question

tap to select uibutton then tap to deselect uibutton

Hi I am trying to implement the following

tap uibutton to select and highlight background then tap the same button again to deselect the uibutton background to original state or another color

my code is as follows:

@IBOutlet weak var case4Btn: UIButton!

@IBAction func case4BtnClicked(sender: AnyObject) { //touch up inside
case4Btn.backgroundColor = UIColor.cyanColor()
@IBAction func case4BtnCancel(sender: AnyObject) {
case4Btn.backgroundColor = UIColor.lightGrayColor()//touch down

with the following code when I tap once it selects and highlights the UIButton button when i tap again it changes color buton does not deselect, in order for me to deselect I have to tap,hold and drag away from the button for it to change color or return to original state

Please help as this is driving me mad, something that seems to be so simple seems to be so hard

Thank you in advance

Answer Source

I would do something like this:

var buttonState = "cyan"
//the color the button should be when pressed

@IBOutlet weak var case4Btn: UIButton!
//the button

@IBAction func case4BtnClicked(sender: AnyObject) {
    //touch up inside
    if(buttonState == "cyan"){
        //if the button is supposed to be cyan
        case4Btn.backgroundColor = UIColor.cyanColor()
        //set the background color
        buttonState = "gray"
        //set it to be gray next time
        //if it isn't
        case4Btn.backgroundColor = UIColor.grayColor()
        //set the background color
        buttonState = "cyan"
        //make it become cyan next time