0

Is there a way to change the color of a customized UIButton when clicked and let it stay the same until clicked again? Currently I overrode drawRect to create the customized button but don't know where to go from there.

EDIT:

class DayButtons: UIButton {

    var isPressed: Bool = false

    var color = UIColor.whiteColor()

        override func drawRect(rect: CGRect) {
        let cornerR = CGFloat(5)       
        var path = UIBezierPath(roundedRect: rect, cornerRadius: cornerR)
        color.setFill()
        path.fill()
    }
}
Liumx31
  • 1,190
  • 1
  • 16
  • 33

1 Answers1

2

Not sure where you're setting the button color, but the code to change the color of the button will look something like this:

yourButton.backgroundColor = UIColor.blueColor() // this would make the button color blue.

You could set the button color programmatically in viewDidLoad and change it when your IBAction is called. For example, you could add this line in your IBAction:

yourButton.backgroundColor = UIColor.redColor()

You may find this post helpful:

Change button background color using swift language

Update

Without seeing the code, I'm not sure what you're trying to do. You can change the fill of the rect with this code: UIColor.whiteColor().setFill().

You could redraw the rect when your button is clicked and tie the color to a Bool. Something like this would go inside the IBAction tied to your button to toggle the state:

if self.myCondition == true { 
    self.myCondition = false
    } else { 
    self.myCondition = true
}

Inside the code you're using to create your rect, you could do something like this:

if self.myCondition == true { 
    UIColor.greenColor().setFill()
    } else { 
    UIColor.redColor().setFill()
}
Community
  • 1
  • 1
Adrian
  • 16,233
  • 18
  • 112
  • 180
  • yea but i'm changing the customized button, instead of the button frame background color, so I was thinking maybe I could redraw the button when clicked. – Liumx31 Jul 05 '15 at 04:29
  • Are you creating the button in Interface Builder or programmatically? What aspect of the button do you wish to change? – Adrian Jul 05 '15 at 12:34
  • programmatically, I basically drew a ovalRect in drawRect and I only want to change the color of that ovalRect. – Liumx31 Jul 05 '15 at 23:44
  • Thanks for the answer, I just added the code for my UIButton subclass. I'm a bit confused about how to call `drawRect` when I press these buttons, because every time I press them they need to be redrawn. – Liumx31 Jul 06 '15 at 01:09