Skip to content

Instantly share code, notes, and snippets.

@yogeshmanghnani
Last active February 24, 2019 12:59
Show Gist options
  • Save yogeshmanghnani/159e46c87cf7028cc732a031d7812905 to your computer and use it in GitHub Desktop.
Save yogeshmanghnani/159e46c87cf7028cc732a031d7812905 to your computer and use it in GitHub Desktop.
Gradients in iOS using Swift
import UIKit
class GradientWrapperView: UIView {
private let gradientLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.borderColor = UIColor.black.cgColor
layer.borderWidth = CGFloat(0.5)
return layer
}()
override func draw(_ rect: CGRect) {
self.layer.addSublayer(gradientLayer)
gradientLayer.frame = self.bounds
gradientLayer.startPoint = self.startPoint
gradientLayer.endPoint = self.endPoint
gradientLayer.colors = self.colors
gradientLayer.type = self.type
}
public var colors: [CGColor] = [UIColor.black.cgColor, UIColor.white.cgColor] {
didSet{
self.gradientLayer.colors = self.colors
}
}
public var startPoint: CGPoint = CGPoint(x: 0, y: 0) {
didSet {
self.gradientLayer.startPoint = startPoint
}
}
public var endPoint: CGPoint = CGPoint(x: 1, y: 0) {
didSet{
self.gradientLayer.endPoint = self.endPoint
}
}
public var type: CAGradientLayerType = .axial {
didSet {
gradientLayer.type = self.type
}
}
}
import UIKit
class MyViewController: UIViewController {
private let gradientLayer: CAGradientLayer = {
let gradient = CAGradientLayer()
gradient.borderWidth = CGFloat(0.5)
gradient.borderColor = UIColor.black.cgColor
gradient.colors = [UIColor.black.cgColor, UIColor.white.cgColor]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 0)
gradient.type = .axial
return gradient
}()
override func viewDidLoad(){
gradientLayer.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
self.view.layer.addSublayer(gradientLayer)
}
//More ViewController Code
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment