This does work for my project
/**
set a gradient to a view
gradientColors must be cgColors
gradientColors and locations must have the same array size
example:
let gradientColors = [UIColor.red.cgColor,UIColor.blue.cgColor,UIColor.yellow.cgColor]
let locations:[NSNumber] = [0.0,0.8,1.0]
*/
static func setGradient(viewWithGradient: UIView, backgroundColor: UIColor, gradientColors: [CGColor], locations:[NSNumber], boundsOfGradient:CGRect) {
if gradientColors.count != locations.count {
print("gradientColors and locations must have same size!")
return
}
viewWithGradient.backgroundColor = backgroundColor
let mask = CAGradientLayer()
mask.colors = gradientColors
mask.locations = locations
mask.frame = boundsOfGradient
viewWithGradient.layer.mask = mask
}
Call like this
let gradientColors = [UIColor.red.cgColor,UIColor.blue.cgColor,UIColor.yellow.cgColor]
let locations:[NSNumber] = [0.0,0.8,1.0]
GeneralTools.setGradient(viewWithGradient: yourViewThatShouldGetGradient, backgroundColor: backgroundColorOfYourViewWithGradient, gradientColors: gradientColors, locations: locations, boundsOfGradient: viewWhereIsYourGradientInside.bounds)
Maybe not clear enough boundsOfGradient: The bounds will be set to your gradients frame. So simply said this will declare the size of your gradient.