Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying gradient background for UIView using auto layout

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

like image 396
Aravind Avatar asked Sep 19 '16 12:09

Aravind


1 Answers

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.

like image 126
TomCobo Avatar answered Sep 20 '22 11:09

TomCobo