Skip to content

Instantly share code, notes, and snippets.

@foxicode
Created April 16, 2020 14:54
Show Gist options
  • Select an option

  • Save foxicode/5e1ccfcd43265085781cd8538d17662d to your computer and use it in GitHub Desktop.

Select an option

Save foxicode/5e1ccfcd43265085781cd8538d17662d to your computer and use it in GitHub Desktop.
iOS gradient view
import UIKit
@IBDesignable
class GradientView: UIView {
enum Direction: Int {
case horizontal
case vertical
}
@IBInspectable var startColor: UIColor = .white {
didSet {
gradientLayer?.colors = [
startColor.cgColor,
endColor.cgColor
]
}
}
@IBInspectable var endColor: UIColor = .black {
didSet {
gradientLayer?.colors = [
startColor.cgColor,
endColor.cgColor
]
}
}
@IBInspectable var direction: Int = Direction.horizontal.rawValue {
didSet {
if direction == Direction.horizontal.rawValue {
gradientLayer?.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer?.endPoint = CGPoint(x: 1.0, y: 0.5)
} else {
gradientLayer?.startPoint = CGPoint(x: 0.5, y: 0.0)
gradientLayer?.endPoint = CGPoint(x: 0.5, y: 1.0)
}
}
}
var gradientLayer: CAGradientLayer? = nil
override func layoutSubviews() {
super.layoutSubviews()
if gradientLayer == nil {
gradientLayer = CAGradientLayer()
gradientLayer!.colors = [
startColor.cgColor,
endColor.cgColor
]
if direction == Direction.horizontal.rawValue {
gradientLayer!.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer!.endPoint = CGPoint(x: 1.0, y: 0.5)
} else {
gradientLayer!.startPoint = CGPoint(x: 0.5, y: 0.0)
gradientLayer!.endPoint = CGPoint(x: 0.5, y: 1.0)
}
layer.addSublayer(gradientLayer!)
}
gradientLayer?.cornerRadius = layer.cornerRadius
gradientLayer?.frame = self.bounds
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment