Interface builder 为渐变视图使用@IBDesignable

Interface builder 为渐变视图使用@IBDesignable,interface-builder,xcode8,cagradientlayer,ibdesignable,ibinspectable,Interface Builder,Xcode8,Cagradientlayer,Ibdesignable,Ibinspectable,我正在使用下面的创建在IB中可见的渐变视图: import UIKit import QuartzCore @IBDesignable class FAUGradientView: UIView { @IBInspectable var firstColor:UIColor = UIColor.clear @IBInspectable var secondColor:UIColor = UIColor.clear @IBInspectable var startPoi

我正在使用下面的创建在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)
    }


}
然而,我在IB中得到的是一个纯黑色视图,而不是具有双色渐变的视图,如下所示:


解决了。它们需要是cgColors,但XCode不会给您一个错误来指示这一点

[firstColor.cgColor, secondColor.cgColor]
上述方法解决了这个问题。

效果很好,但是

self.gradientLayer.frame = self.frame
应该是

self.gradientLayer.frame = self.bounds
或者,根据视图在父视图中的位置,可以获得一些非常奇怪的绘制偏移