iosswiftstoryboardcagradientlayer

CAGradientLayer not taking full width


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


Solution

  • 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