Applying gradient background for UIView using auto layout

Layers do not autoresize them self. To fix this issue you should change layer frame. This is one way how it is possible to implement:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    //Update you're layer based on the new frame
    self.view.addGradientWithColor()

 }

You can subclass the UIView and override drawRect method where you add your gradient.

Updated to Swift 4


class GradientView: UIView {

    private let gradient : CAGradientLayer = CAGradientLayer()
    private let gradientStartColor: UIColor
    private let gradientEndColor: UIColor

    init(gradientStartColor: UIColor, gradientEndColor: UIColor) {
        self.gradientStartColor = gradientStartColor
        self.gradientEndColor = gradientEndColor
        super.init(frame: .zero)
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }

    override func layoutSublayers(of layer: CALayer) {
        super.layoutSublayers(of: layer)
        gradient.frame = self.bounds
    }

    override public func draw(_ rect: CGRect) {
        gradient.frame = self.bounds
        gradient.colors = [gradientEndColor.cgColor, gradientStartColor.cgColor]
        gradient.startPoint = CGPoint(x: 1, y: 0)
        gradient.endPoint = CGPoint(x: 0.2, y: 1)
        if gradient.superlayer == nil {
            layer.insertSublayer(gradient, at: 0)
        }
    }
}

After you create your UIView you just need to add your constraints to that view.


you could save a reference to the layer, and adjust it's frame in the views layoutSublayersOfLayer method. this could be outsourced in an UIView subclass:

class GradientView: UIView {

private let gradient : CAGradientLayer = CAGradientLayer()

/**
 displays a gradient on the view
 */
func addGradient() {

    self.gradient.frame     = self.bounds
    self.gradient.colors    = [gradientEndColor.CGColor, gradientStartColor.CGColor]
    gradient.startPoint     = CGPointMake(1,0)
    gradient.endPoint       = CGPointMake(0.2,1)        
    self.layer.insertSublayer(self.gradient, atIndex: 0)
}

/**
 resizes the gradient with the view size
 */
override func layoutSublayers(of layer: CALayer) {
    super.layoutSublayers(of: layer)
    self.gradient.frame = self.bounds
}
}