Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.