In Case if anyone need Swift 3.X
func addLinearGradientToView(view: UIView, colour: UIColor, transparntToOpaque: Bool, vertical: Bool)
{
let gradient = CAGradientLayer()
let gradientFrame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
gradient.frame = gradientFrame
var colours = [
colour.cgColor,
colour.withAlphaComponent(0.9).cgColor,
colour.withAlphaComponent(0.8).cgColor,
colour.withAlphaComponent(0.7).cgColor,
colour.withAlphaComponent(0.6).cgColor,
colour.withAlphaComponent(0.5).cgColor,
colour.withAlphaComponent(0.4).cgColor,
colour.withAlphaComponent(0.3).cgColor,
colour.withAlphaComponent(0.2).cgColor,
colour.withAlphaComponent(0.1).cgColor,
UIColor.clear.cgColor
]
if transparntToOpaque == true
{
colours = colours.reversed()
}
if vertical == true
{
gradient.startPoint = CGPoint(x: 0, y: 0.5)
gradient.endPoint = CGPoint(x: 0, y: 0.5)
}
gradient.colors = colours
view.layer.insertSublayer(gradient, at: 0)
}
Other way in Swift 3.x
let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.blue.cgColor, UIColor.white.cgColor]
view.layer.insertSublayer(gradient, at: 0)