Skip to content

Instantly share code, notes, and snippets.

@fxm90
Last active January 25, 2026 14:49
Show Gist options
  • Select an option

  • Save fxm90/9604b0a067af46f68b80c6968736558d to your computer and use it in GitHub Desktop.

Select an option

Save fxm90/9604b0a067af46f68b80c6968736558d to your computer and use it in GitHub Desktop.
An image view containing a vertical gradient as background.
//
// VerticalGradientImageView.swift
//
// Created by Felix Mau on 23/09/18.
// Copyright © 2018 Felix Mau. All rights reserved.
//
import UIKit
final class VerticalGradientImageView: UIImageView {
// MARK: - Public Properties
/// > By overriding `layerClass` you can tell UIKit what CALayer class to use for a UIView's backing layer.
/// > That way you can reduce the amount of layers, and don't have to do any manual layout.
///
/// [John Sundell - Custom UIView backing layers](https://twitter.com/johnsundell/status/1000099872580816897)
override class var layerClass: AnyClass {
CAGradientLayer.self
}
var colors = [UIColor]() {
didSet {
gradientLayer?.colors = colors.map(\.cgColor)
}
}
// MARK: - Private Properties
private var gradientLayer: CAGradientLayer? {
layer as? CAGradientLayer
}
// MARK: - Instance Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
setUpGradientLayer()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpGradientLayer()
}
// MARK: - Private Methods
private func setUpGradientLayer() {
gradientLayer?.startPoint = .zero
gradientLayer?.endPoint = CGPoint(x: 0, y: 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment