Skip to content

Instantly share code, notes, and snippets.

@fxm90
Last active February 11, 2019 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fxm90/9604b0a067af46f68b80c6968736558d to your computer and use it in GitHub Desktop.
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
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.
///
/// Source: [John Sundell - Custom UIView backing layers](https://twitter.com/johnsundell/status/1000099872580816897)
override class var layerClass: AnyClass {
return CAGradientLayer.self
}
var colors: [UIColor] = [] {
didSet {
gradientLayer?.colors = colors.map({ $0.cgColor })
}
}
// MARK: - Private properties
private var gradientLayer: CAGradientLayer? {
return layer as? CAGradientLayer
}
// MARK: - Constructor
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