Last active
September 19, 2016 03:04
-
-
Save leilee/66eb09f6309c040646734fe82e093d9f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class GradientView: UIView { | |
@IBInspectable var startColor: UIColor? | |
@IBInspectable var endColor: UIColor? | |
@IBInspectable var horizontal: Bool = true { | |
didSet { | |
let horizontalStartPoint = CGPoint(x: 0, y: 0.5) | |
let horizontalEndPoint = CGPoint(x: 1, y: 0.5) | |
let verticalStartPoint = CGPoint(x: 0.5, y: 0) | |
let verticalEndPoint = CGPoint(x: 0.5, y: 1) | |
gradientLayer.startPoint = horizontal ? horizontalStartPoint : verticalStartPoint | |
gradientLayer.endPoint = horizontal ? horizontalEndPoint : verticalEndPoint | |
} | |
} | |
var colors: [UIColor] { | |
set { | |
gradientLayer.colors = newValue.map({ $0.CGColor }) | |
} | |
get { | |
guard let cgColors = gradientLayer.colors as? [CGColor] else { | |
return [] | |
} | |
return cgColors.map({ UIColor(CGColor: $0) }) | |
} | |
} | |
override func awakeFromNib() { | |
super.awakeFromNib() | |
if let start = startColor, let end = endColor { | |
colors = [start, end] | |
} | |
} | |
} | |
extension GradientView { | |
override class func layerClass() -> AnyClass { | |
return CAGradientLayer.self | |
} | |
var gradientLayer: CAGradientLayer { | |
return self.layer as! CAGradientLayer | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment