How to create a UIProgressView with gradient progress in Swift
I am an iOS engineer, and last week I was converting a UI design into a screen on Xcode's interface builder, when I faced this layout:
So, the designer wanted a progress view containing a gradient fill, and this is how I built it on code:
First of all, I've created a UIImage
extension to initiate it with an array of UIColor
, which will be turned into a gradient. Also, I created a GradientOrientation
enum to specify if the gradient is vertical or horizontal. This way, we can use the UIImage
init in other UI components, such as UIImageView
.
Finally I've created the GradientProgressView
, a class extended from UIProgressView
which contains firstColor
and secondColor
. These variables were marked as IBInspectable
, so they can be assigned at the Interface Builder. By changing these colors either on storyboard or on code, the progress view's progressImage
will be set as a gradient starting at firstColor
and ending at secondColor
.
That being done, we just need to change the GradientProgressView
's first and second colors and voilà, our progress views are now gradient-ready.