title: Applying CAGradientLayer on Dynamically Sized UITableViewCell
body: <p><strong>Background:</strong> My app allows users to select a gradient border to apply to UITableViewCells that are dynamically sized based on the content within them. I am currently creating this border by inserting a CAGradientLayer sublayer to a UIView that sits within the cell.</p>
  <p><strong>Issue:</strong> Because each cell is sized differently, I am resizing the CAGradientLayer by overriding layoutIfNeeded in my custom cell class. This works, but seems suboptimal because the border is being redrawn over and over again and flickers as the cell is resizing.</p>
  <p><strong>Link to Screen Capture:</strong>
  <a href="https://drive.google.com/file/d/1SiuNozyUM7LCdYImZoGCWeoeBKu2Ulcw/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1SiuNozyUM7LCdYImZoGCWeoeBKu2Ulcw/view?usp=sharing</a></p>
  <p><strong>Question:</strong> Do I need to take a different approach to creating this border? Or am I missing something regarding the UITableViewCell lifecycle? I have come across similar issues on SO, but none that seem to address this redraw issue. Thank you for your help.</p>
  <p><strong>CAGradientLayer Extension to Create Border</strong></p>
  <pre><code>extension CAGradientLayer {
      
      func createBorder(view: UIView, colors: [CGColor]) {
          self.frame =  CGRect(origin: CGPoint.zero, size: view.bounds.size)
          self.colors = colors
          
          let shape = CAShapeLayer()
          shape.lineWidth = 14
          shape.path = UIBezierPath(roundedRect: view.bounds, cornerRadius: 12).cgPath
          shape.strokeColor = UIColor.black.cgColor
          shape.fillColor = UIColor.clear.cgColor
          self.mask = shape
      }
  }
  </code></pre>
  <p><strong>TableViewCell Class - Insert CAGradientLayer</strong></p>
  <pre><code>override func awakeFromNib() {
     super.awakeFromNib()           
     reportCard.layer.insertSublayer(gradientLayer, at: 0)
     ...
  }
  </code></pre>
  <p><strong>TableViewCell Class - Resize the Border and Apply User Selected Design</strong></p>
  <pre><code>override func layoutIfNeeded() {
          super.layoutIfNeeded()
              
          switch currentReport?.frameId {
          case &quot;sj_0099_nc_frame_001&quot;:
              gradientLayer.createBorder(view: reportCard, colors: [App.BorderColors.lavender, App.BorderColors.white])
          case &quot;sj_0099_nc_frame_002&quot;:
              gradientLayer.createBorder(view: reportCard, colors: [App.BorderColors.red, App.BorderColors.white])
          case &quot;sj_0099_nc_frame_003&quot;:
              gradientLayer.createBorder(view: reportCard, colors: [App.BorderColors.yellow, App.BorderColors.white])
          default:
              gradientLayer.createBorder(view: reportCard, colors: [App.BorderColors.white, App.BorderColors.white])
          }
   }
  </code></pre>