Skip to content

Instantly share code, notes, and snippets.

@Alec-Barton
Last active December 2, 2022 21:43
Show Gist options
  • Save Alec-Barton/4b995bd8f5e6e7fc36bcb5ccbb56fb30 to your computer and use it in GitHub Desktop.
Save Alec-Barton/4b995bd8f5e6e7fc36bcb5ccbb56fb30 to your computer and use it in GitHub Desktop.
UIView containing a CAGradientLayer that will automatically update in response to changes to light/dark mode
// GradientView.swift
//
// UIView containing a CAGradientLayer that will automatically update in response to changes to light/dark mode
import UIKit
// MARK: - GradientView
public class GradientView: UIView {
// MARK: GradientView (Initializers)
public init(frame: CGRect,
colors: [UIColor],
startPoint: CGPoint,
endPoint: CGPoint,
locations: [NSNumber],
cornerRadius: CGFloat = 0) {
self.colors = colors
super.init(frame: frame)
layer.cornerRadius = cornerRadius
let cgColors = cgColors(for: colors)
gradientLayer.frame = bounds
gradientLayer.colors = cgColors
gradientLayer.startPoint = startPoint
gradientLayer.endPoint = endPoint
gradientLayer.locations = locations
gradientLayer.cornerRadius = layer.cornerRadius
gradientLayer.masksToBounds = true
layer.addSublayer(gradientLayer)
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
// MARK: GradientView (Public Methods)
public override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
gradientLayer.frame = self.bounds
}
public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
let cgColors = cgColors(for: colors)
gradientLayer.colors = cgColors
}
// MARK: GradientView (Private Properties)
private var gradientLayer: CAGradientLayer = CAGradientLayer()
private let colors: [UIColor]
// MARK: GradientView (Private Methods)
private func cgColors(for uiColors: [UIColor]) -> [CGColor] {
return uiColors.map({ $0.cgColor })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment