Gradient view not working programmatically with swift

2442 views ios
9

Hi guys please am trying to make a view inherit from a gradient UIView with a background to it but for one or two reasons its not inheriting. Here is my code:

// The gradient class I want to be inherited from
class GradientView: UIView {

    var gradient = CAGradientLayer()

    override func awakeFromNib() {
        super.awakeFromNib()
        setupGradientView()
    }

    func setupGradientView(){
        gradient.frame = self.bounds
        gradient.colors = [UIColor.white.cgColor, UIColor.init(white:1.0, alpha: 0.0).cgColor]
        gradient.startPoint = CGPoint.zero
        gradient.endPoint = CGPoint(x: 0, y: 1)
        gradient.locations = [0.8,1.0]
        self.layer.addSublayer(gradient)
    }

}

let headerHolder: GradientView = {
        let view = GradientView()
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

//Where i set up the views
  func setupViews() {
    view.addSubview(headerHolder)
            headerHolder.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
            headerHolder.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
            headerHolder.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
            headerHolder.heightAnchor.constraint(equalToConstant: 80).isActive = true
}

answered question

1 Answer

8

You need to call it inside

override func layoutSubviews{}

as awakeFromNib is not called in such init cases , also where bounds has a non-zeros value

posted this

Have an answer?

JD

Please login first before posting an answer.