Castro Zwelithini Castro Zwelithini - 20 days ago 6
Swift Question

Gradient view not working when added programmatically

So my Class looks like this :

import UIKit

class GradientBarView: UIView {

override init(frame: CGRect) { // for using CustomView in code
super.init(frame: frame)
commonInit()

}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}

func commonInit() {

let gradient = CAGradientLayer()
gradient.frame = bounds
gradient.startPoint = CGPoint(x: 0, y: 0.5)
gradient.endPoint = CGPointMake(1, 0.5)
gradient.colors = [AppColor.SecondaryGreen.CGColor, AppColor.HeritageGreen.CGColor, AppColor.HeritageGreen.CGColor]
layer.insertSublayer(gradient, atIndex: 0)

translatesAutoresizingMaskIntoConstraints = false

}

}


and this is how I use it(in my viewDidLoad)

let gradientBar = GradientBarView(frame: CGRectZero)
self.view.addSubview(gradientBar)


Then add the necessary constraints(which is fine)...so the problem is that the view is just black but if i add it via the Storyboard it works just fine

please help,what am i missing?

Thanks

Answer

Your frame is CGRectZero by the time you call gradient.frame = bounds in commonInit. Thus your bounds will also be CGRectZero. Thus the frame you are inserting has no height or width.

You can add the gradient in the draw method of your custom view. override func draw(_ rect: CGRect) Just ensure that you do not add it more than once.

Alternatively add it to layoutSubviews, depending on your use. Something like:

class GradientBarView: UIView {

    var gradientLayer: CAGradientLayer?

    override init(frame: CGRect) { // for using CustomView in code
        super.init(frame: frame)
        commonInit()

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        translatesAutoresizingMaskIntoConstraints = false
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        gradientLayer?.removeFromSuperlayer()
        gradientLayer = self.addHorizontalGradient(color: UIColor.blue)
    }

}

extension UIView {

    func addHorizontalGradient(color: UIColor) -> CAGradientLayer {
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.startPoint = CGPoint(x:0,y:0.5)
        gradient.endPoint = CGPoint(x:1,y:0.5)
        gradient.colors = [color.cgColor, UIColor.white.withAlphaComponent(0).cgColor]
        self.layer.insertSublayer(gradient, at: 0)
        return gradient
    }

}
Comments