0

I have an extension to add gradient to a view.

    func applyLinearGradient(firstColor: UIColor, secondColor: UIColor, startPoint: CGPoint, endpoint: CGPoint, locations: [NSNumber]) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [firstColor.cgColor, secondColor.cgColor]
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endpoint
        gradientLayer.locations = locations
        gradientLayer.frame = bounds
        
        layer.insertSublayer(gradientLayer, at: 0)
    }
    @IBOutlet weak var titleView: UIView!
    @IBOutlet weak var titleTxt: UILabel!
    
    ...

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        //add gradient under the title
        titleView.applyLinearGradient(firstColor: UIColor(named: "PrimaryColor") ?? UIColor.clear, secondColor: UIColor.clear, startPoint: CGPoint(x: 0.5, y: 1.0), endpoint: CGPoint(x: 0.5, y: 0.0), locations: [0, 1])
    }

The problem is that when I call it in viewDidLayoutSubviews it's applied 2 times. enter image description here

I can just create a gradientview that extends from uiview, but is it possible to make it work with just an extension?

I'm using storyboards.

kironet
  • 766
  • 2
  • 11
  • 27

0 Answers0