Advertisement
Don_Mag

Untitled

Jun 6th, 2023
1,617
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.97 KB | None | 0 0
  1. class ViewController: UIViewController {
  2.    
  3.     override func viewDidLoad() {
  4.         super.viewDidLoad()
  5.        
  6.         let g = view.safeAreaLayoutGuide
  7.        
  8.         let gv = Gradient()
  9.         gv.translatesAutoresizingMaskIntoConstraints = false
  10.         view.addSubview(gv)
  11.        
  12.         NSLayoutConstraint.activate([
  13.             gv.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
  14.             gv.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
  15.             gv.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
  16.             gv.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -20.0),
  17.         ])
  18.        
  19.         //gv.diagonalMode = true
  20.         //gv.horizontalMode = true
  21.        
  22.         view.backgroundColor = .systemYellow
  23.     }
  24.    
  25. }
  26.  
  27. class Gradient: UIView {
  28.     var startColor:   UIColor = .white { didSet { updateColors() }}
  29.     var endColor:     UIColor = .red { didSet { updateColors() }}
  30.     var horizontalMode:  Bool =  false { didSet { updatePoints() }}
  31.     var diagonalMode:    Bool =  false { didSet { updatePoints() }}
  32.    
  33.     override class var layerClass: AnyClass { CAGradientLayer.self }
  34.    
  35.     var gradientLayer: CAGradientLayer { layer as! CAGradientLayer }
  36.    
  37.     override init(frame: CGRect) {
  38.         super.init(frame: frame)
  39.         commonInit()
  40.     }
  41.     required init?(coder: NSCoder) {
  42.         super.init(coder: coder)
  43.         commonInit()
  44.     }
  45.     private func commonInit() {
  46.         updatePoints()
  47.         updateLocations()
  48.         updateColors()
  49.     }
  50.    
  51.     func updatePoints() {
  52.         if horizontalMode {
  53.             gradientLayer.startPoint = diagonalMode ? .init(x: 1, y: 0) : .init(x: 0, y: 0.5)
  54.             gradientLayer.endPoint   = diagonalMode ? .init(x: 0, y: 1) : .init(x: 1, y: 0.5)
  55.         } else {
  56.             gradientLayer.startPoint = diagonalMode ? .init(x: 0, y: 0) : .init(x: 0.5, y: 0)
  57.             gradientLayer.endPoint   = diagonalMode ? .init(x: 1, y: 1) : .init(x: 0.5, y: 1)
  58.         }
  59.     }
  60.     func updateLocations() {
  61.         gradientLayer.locations = [0, 0.5, 0.5, 1.0]
  62.     }
  63.     func updateColors() {
  64.         gradientLayer.colors = [startColor.cgColor, startColor.cgColor, endColor.cgColor, endColor.cgColor]
  65.     }
  66.    
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement