Is there a way to make gradient background color in the interface builder?

前端 未结 9 1151
终归单人心
终归单人心 2021-01-30 13:08

For my application I\'m using a TableView and using customized UITableViewCells.

I customized my cells via interface builder, not programmatically. Is there a way to als

9条回答
  •  后悔当初
    2021-01-30 13:47

    answer by etayluz works fine but I added a couple changes:

    1. Gradient size defined by own layer bounds, not the superview.
    2. Remove Gradient layer on every draw, so that it does not keep drawing and adding a new layer when redraw is necessary (for instance by calling .setNeedsDisplay() on rotation).

      @IBDesignable final class MFGradientView: UIView {
      
          @IBInspectable var startColor: UIColor = UIColor.clear
          @IBInspectable var endColor: UIColor = UIColor.clear
      
          override func draw(_ rect: CGRect) {
             layer.sublayers?.first?.removeFromSuperlayer()
      
             let gradient: CAGradientLayer = CAGradientLayer()
             gradient.frame = CGRect(origin: CGPoint.zero, size: self.bounds.size)
             gradient.colors = [startColor.cgColor, endColor.cgColor]
             layer.insertSublayer(gradient, at: 0)
          }
      } 
      

提交回复
热议问题