0

I want to add a gradient view. But it is not taking the full width. How can I solve this issue?

I share my code here:

import UIKit
import SwiftHEXColors

extension UIView {

    func applyGradient(isVertical: Bool, colorArray: [UIColor]) {
        layer.sublayers?.filter({ $0 is CAGradientLayer }).forEach({ $0.removeFromSuperlayer() })
        
         
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = colorArray.map({ $0.cgColor })
        if isVertical {
            //top to bottom
            gradientLayer.locations = [0.0, 1.0]
        } else {
            //left to right
            gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
            gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
        }
        
        backgroundColor = .clear
        gradientLayer.frame = self.bounds
        layer.insertSublayer(gradientLayer, at: 0)
//        layer.masksToBounds = true
        autoresizingMask = [.flexibleWidth, .flexibleHeight]
    }
    
    func applyAPPGradient() {
        self.applyGradient(isVertical: true, colorArray: [
            UIColor(red: 0.039, green: 0.318, blue: 0.631, alpha: 1),
            UIColor(red: 0.02, green: 0.161, blue: 0.318, alpha: 1)
        ])
    }
}

enter image description here

HangarRash
  • 7,314
  • 5
  • 5
  • 32
Rasel Khan
  • 2,976
  • 19
  • 25
  • That is a bad approach. Layers do not resize with the view. You should use a custom `UIView` subclass, and either make its base layer a gradient layer, or add a gradient layer as a sublayer and update the layer frame in `layoutSubviews()`. – DonMag Apr 10 '23 at 11:20

1 Answers1

1

your code maybe call before the render and before counting the correct width (probably your UI is on iPhone 14 pro and your render in simulator is on iPhone 14 pro MAX)

you can add the code in

DispatchQueue.main.async {
            ... your Gradient Code
}

or

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
           ... your Gradient Code
 }

this code (delay) helps that first perform the render and after that count the correct width

Maziar Saadatfar
  • 1,286
  • 1
  • 5
  • 11