gbdcool gbdcool - 3 months ago 19
iOS Question

Swift 3.0: Change a button color once pressed

I've created a circular green button. Here is the CircularButton.swift where I've defined color and shape as below:

import UIKit

class CircularButton: UIButton {

@IBInspectable var fillColor: UIColor = UIColor.green

override func draw(_ rect: CGRect) {

let path = UIBezierPath(ovalIn: rect)
fillColor.setFill()
path.fill()

}
}


Here is the screen shot.

enter image description here

On the button pressed I would like to change its color to red. I've defined the function as below:

@IBAction func circularButtonPressed(_ sender: CircularButton) {
sender.fillColor = UIColor.red
sender.draw(CGRect(x: 0, y: 0, width: sender.frame.width,
height: sender.frame.height))
}


Any idea why the color is not changed to red?

Note: If I add below line:

sender.backgroundColor = UIColor.white


in the above function, the button color changes to red.

Thank you for your help.

Answer

You should not call draw(_:) from inside your code directly. You just need to tell iOS that the control needs to be redrawn.

Remove the line calling draw(_:):

@IBAction func circularButtonPressed(_ sender: CircularButton) {
    sender.fillColor = UIColor.red
}

And add observer to the fillColor property:

@IBInspectable var fillColor: UIColor = UIColor.green {
    didSet(oldColor) {
        if fillColor != oldColor {
            self.setNeedsDisplay()
        }
    }
}