gbdcool gbdcool - 2 months ago 16x
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 =

override func draw(_ rect: CGRect) {

let path = UIBezierPath(ovalIn: rect)


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 =
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.


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 =

And add observer to the fillColor property:

@IBInspectable var fillColor: UIColor = {
    didSet(oldColor) {
        if fillColor != oldColor {