Set the Fill Color for a UIView

Posted 03/19/2016 9:49 PM by Corey Klass

On a UIView, you're able to set the backgroundColor property to change the background color of the view. This works, most of the time.

Unfortunately, when you change the background color when the view is loaded in a UITableViewCell, the background color disappears when the table cell is selected. The solution is to create a subclass of UIView and override the drawRect() function to manually draw a fill color into the view bounds.

When you reset the fill color, the call to self.setNeedsDisplay() tells the UIView to redraw itself with the new color.

    //  CKFillView.swift

    class CKFillView: UIView {

        private var _fillColor = UIColor.whiteColor()

        // set this variable to the color that you want to fill
        var fillColor: UIColor {
            get {
                return self._fillColor
            set {
                if (self._fillColor != newValue) {
                    self._fillColor = newValue

        // draw the entire rect with the fill color
        override func drawRect(rect: CGRect) {
            let context = UIGraphicsGetCurrentContext()

            let colorComponents = CGColorGetComponents(self.fillColor.CGColor)
            let red = colorComponents[0]
            let green = colorComponents[1]
            let blue = colorComponents[2]
            let alpha = CGColorGetAlpha(self.fillColor.CGColor)

            CGContextSetRGBFillColor(context, red, green, blue, alpha)

            CGContextFillRect(context, rect)