Gradient Colour Not Properly worked on UIView Swift

60 Views Asked by At

Here is what I am trying to do:

original screen shot

The screenshot is taken from Iphone:

trying give result

This is my code:

import UIKit

class GradientController: UIViewController {    
    @IBOutlet weak var viewBottomBorder: UIView!
    
    lazy var gradient: CAGradientLayer = {
        let gradient = CAGradientLayer()
        gradient.type = .axial
        gradient.colors = [UIColor.clear.cgColor,UIColor.black.cgColor]
        gradient.locations = [0, 1]
        return gradient
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gradient.frame = view.bounds
        viewBottomBorder.layer.addSublayer(gradient)
    }
}

Question: How to show same bottom gradient colour the view?

Can someone please explain to me how to solve this? I've tried to solve this issue but no results yet.

2

There are 2 best solutions below

0
DonMag On

You can save yourself a lot of work and extra code by using a UIView subclass such as this:

class GradientView: UIView {
    
    override class var layerClass: AnyClass { CAGradientLayer.self }
    private var gradientLayer: CAGradientLayer { layer as! CAGradientLayer }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    private func commonInit() {
        self.backgroundColor = .clear
        gradientLayer.colors = [UIColor.clear.cgColor,UIColor.black.cgColor]
    }
    
}

Now, in Storyboard, set the Custom Class of your viewBottomBorder to GradientView, and your controller code becomes:

import UIKit

class GradientController: UIViewController {    
    @IBOutlet weak var viewBottomBorder: GradientView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}
0
Navneet Kaur On
func Gradient(colours: [UIColor]) -> CAGradientLayer {
    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = bounds
    gradientLayer.colors = colours.map { $0.cgColor }
    gradientLayer.locations = [0.0, 1.0]
    gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
    return gradientLayer
}

try using this code it will work for you also you can change start and end points as per requirements.

Attaching image for reference.

enter image description here