Applying gradient background for UIView using auto layout

Aravind picture Aravind · Sep 19, 2016 · Viewed 8.3k times · Source

I extended UIView to add a addGradientWithColor() method to get the gradient background:

 extension UIView {
   func addGradientWithColor() {
     let gradient = CAGradientLayer()
     gradient.frame = self.bounds
     gradient.colors = [gradientEndColor.CGColor,  gradientStartColor.CGColor]
     gradient.startPoint = CGPointMake(1,0)
     gradient.endPoint = CGPointMake(0.2,1)
    self.layer.insertSublayer(gradient, atIndex: 0)
  } } 

My issue is when I run landscape mode, the UIView is not stretched

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.view.addGradientWithColor() }

I tried to calling viewDidLayoutSubviews() but its not working properly

Here is the screen shot:

after removing viewDidLayoutSubviews() enter image description here

Answer

TomCobo picture TomCobo · Sep 20, 2016

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.