Aravi Aravi - 1 month ago 19x
iOS Question

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() {
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


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 layoutSublayersOfLayer(layer: CALayer) {
    self.gradient.frame = self.bounds