0

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

steventnorris
  • 5,656
  • 23
  • 93
  • 174

2 Answers2

1

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.

steventnorris
  • 5,656
  • 23
  • 93
  • 174
0

Works well, but;

self.gradientLayer.frame = self.frame

should be

self.gradientLayer.frame = self.bounds

or you can get some very odd draw offsets depending on where the view is within the parent

kric
  • 114
  • 5