Это работает для моего проекта
/**
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
}
Звоните вот так
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)
Возможно, не достаточно ясно boundsOfGradient
: границы будут установлены в рамке вашего градиента.Проще говоря, это объявит размер вашего градиента.