interface-builderxcode8cagradientlayeribdesignableibinspectable

Using @IBDesignable for a gradient view


I am using the below to create a gradient view that is visible in IB:

import UIKit
import QuartzCore

@IBDesignable
class FAUGradientView: UIView {

    @IBInspectable var firstColor:UIColor = UIColor.clear
    @IBInspectable var secondColor:UIColor = UIColor.clear
    @IBInspectable var startPoint:CGPoint = CGPoint(x: 0.0, y: 1.0)
    @IBInspectable var endPoint:CGPoint = CGPoint(x: 1.0, y:0.0)

    var gradientLayer:CAGradientLayer!

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        gradientLayer = CAGradientLayer()
        self.gradientLayer.colors = [firstColor, secondColor]
        self.gradientLayer.startPoint = self.startPoint
        self.gradientLayer.endPoint = self.endPoint
        self.gradientLayer.frame = self.frame
        self.layer.addSublayer(self.gradientLayer)
    }


}

However, what I get in IB is a solid black view, not a view with a two color gradient, as seen below:

enter image description here


Solution

  • Solved it. They need to be cgColors, but XCode doesn't give you a single error to indicate that.

    [firstColor.cgColor, secondColor.cgColor]
    

    The above fixes the issue.