title: Changing view gradient background in real time
body: <p>I am practicing with gradient backgrounds for a bigger app and created this dummy app to simplify the concept. The view has a 50/50 gradient background and 2 rows of colored buttons. </p>
  
  <p>I want the user to be able to play with colors of the gradient by tapping upper and lower buttons, so that gradient background changes accordingly to buttons color.</p>
  
  <p><a href="https://i.stack.imgur.com/IHj5X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IHj5X.png" alt="enter image description here"></a></p>
  
  <p>ViewController's code is following:</p>
  
  <pre><code>    import UIKit
  
      class ViewController: UIViewController {
  
          var currentUpperColor = UIColor.black
          var currentLowerColor = UIColor.white
  
          override func viewDidLoad() {
              super.viewDidLoad()
  
              setGradientBackground(lowerColor: currentLowerColor, upperColor: currentUpperColor)
          }
  
          func setGradientBackground(lowerColor: UIColor, upperColor: UIColor) {
  
              let gradientLayer = CAGradientLayer()
              gradientLayer.frame = view.bounds
              gradientLayer.colors = [lowerColor.cgColor, upperColor.cgColor]
              gradientLayer.locations = [0.5, 1.0]
              gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
              gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.0)
  
              view.layer.insertSublayer(gradientLayer, at: 0)
  
          }
  
          @IBAction func upperColorPicked(_ sender: UIButton) {
              currentUpperColor = sender.backgroundColor!
              setGradientBackground(lowerColor: currentLowerColor, upperColor: currentUpperColor)
          }
  
          @IBAction func lowerColorPicked(_ sender: UIButton) {
              currentLowerColor = sender.backgroundColor!
              setGradientBackground(lowerColor: currentLowerColor, upperColor: currentUpperColor)
          }
  
          override func didReceiveMemoryWarning() {
              super.didReceiveMemoryWarning()
              // Dispose of any resources that can be recreated.
          }
  
  
  }
  </code></pre>
  
  <p>But when the app runs, nothing happens when buttons are tapped. I understand some kind of view redraw should occur, but I'm not sure how to call it.</p>