Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active December 29, 2016 23:38
Show Gist options
  • Save robertmryan/963240c9b7f9d22c72fb1711c1da2f88 to your computer and use it in GitHub Desktop.
Save robertmryan/963240c9b7f9d22c72fb1711c1da2f88 to your computer and use it in GitHub Desktop.
Cocoa IBDesignable gradient view
// GradientView.swift
//
// Created by Robert Ryan on 12/29/16.
// Copyright © 2016 Robert Ryan. All rights reserved.
//
import Cocoa
@IBDesignable
public class GradientView: NSView {
@IBInspectable public var margin: CGFloat = 5 { didSet { needsLayout = true } }
@IBInspectable public var startColor: NSColor = #colorLiteral(red: 0, green: 0.4772562545, blue: 1, alpha: 1) { didSet { updateColors() } }
@IBInspectable public var endColor: NSColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1) { didSet { updateColors() } }
private var gradientLayer: CAGradientLayer!
convenience init() {
self.init(frame: .zero)
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
configure()
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
private func configure() {
wantsLayer = true
gradientLayer = CAGradientLayer()
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
gradientLayer.name = "gradientLayer"
updateColors()
}
override public func layout() {
super.layout()
if gradientLayer.superlayer == nil {
layer!.addSublayer(gradientLayer)
gradientLayer.contentsScale = layer!.contentsScale
}
gradientLayer.frame = bounds.insetBy(dx: margin, dy: margin)
}
private func updateColors() {
gradientLayer.colors = [startColor, endColor].map { $0.cgColor }
}
}
@robertmryan
Copy link
Author

@robertmryan
Copy link
Author

By the way, I made this @IBDesignable (so put it in a separate framework target and you can then use this view in Interface Builder), but you don't have to do that if you don't want to. Also, I made the margin and the colors @IBInspectable, that way you can customize this right in Interface Builder. Again, not necessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment