Meditations and Learnings

Meditations and Learnings

Simple Gradients for iOS in Swift

When a view calls for a gradient it is easy to just insert a CAGradientLayer into the view’s layer and be done with it. The problem on iOS is that there is no easy way to dynamically resize the gradient with the view’s frame, and this is made worse when working with a gradient over the top of a UIImageView. The best way to solve this is to subclass UIView, make it a gradient, and then add it the storyboard with whatever constraints are appropriate. The view would look like this:

import UIKit
//  MARK: Gradient View
internal final class GradientView: UIView { }
//  MARK: Layer
internal extension GradientView {
	override class var layerClass: Swift.AnyClass { return CAGradientLayer.self }
}
//  MARK: Lifecycle
internal extension GradientView {
	override func awakeFromNib() {
		super.awakeFromNib()
		guard let gradientLayer = layer as? CAGradientLayer else { fatalError() }
		gradientLayer.colors = [UIColor.emBlack.cgColor, UIColor.black.withAlphaComponent(0.5).cgColor]
		gradientLayer.locations = [0.0, 1.0]
	}
}