Swift – UIView gradient extension

Sometimes can be useful to add a gradient on a UIView. This simple UIView extension helps you “coloryze” your screen.

Let see how to use and how is implemented.


import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.applyGradient( colors: [
            UIColor.systemRed,
            UIColor.systemGreen,
            UIColor.systemBlue
        ], locations: [0.0, 0.8, 1.0])
    }
}

The result of the code snippet above is shown in the screenshot on top.

We have three colors, “red“, “green” and “blue” as gradient, positioned starting from 0.0 (red) to 0.8 (green) to 1.0 (blue).


Why between 0.0 and 1.0?

The gradient stops are specified as values between 0 and 1. The values must be monotonically increasing. If nil, the stops are spread uniformly across the range. Defaults to nil.

https://developer.apple.com/documentation/quartzcore/cagradientlayer/1462410-locations?changes=_9

The location is calculated in a range from 0 and 1. All doubles inside are considered valid.


UIView Extension

The extension take as parameter an array of UIColors and optionally an array of NSNumber? that are the locations explained above.

If locations are null, the locations are automatically divided in equal parts, like this:

self.view.applyGradient( colors: [
    UIColor.systemRed,
    UIColor.systemGreen,
    UIColor.systemBlue
], locations: nil)

Add in your code this UIView extension and the game is done:

extension UIView {
    func applyGradient( colors: [UIColor], locations: [NSNumber]? ) {
        assert(colors.count >= 2, "Colors must be at least 2.")
        if locations != nil {
            assert(colors.count == locations?.count, "Locations must have the same size of color array.")
        }
        let gradient = CAGradientLayer()
        gradient.colors = colors.map { $0.cgColor }
        gradient.locations = locations
        gradient.frame = self.bounds
        self.layer.insertSublayer(gradient, at: 0)
    }
}

Have fun.

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.