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

Serdar Dogruyol picture Serdar Dogruyol · Nov 17, 2011 · Viewed 47k times · Source

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 also make the background color of my customized cell a gradient in the interface builder?

Thanks.

Answer

etayluz picture etayluz · Dec 4, 2016

This works for Swift 3.0: (Updated for Swift 4.0)

@IBDesignable
final class GradientView: UIView {
    @IBInspectable var startColor: UIColor = UIColor.clear
    @IBInspectable var endColor: UIColor = UIColor.clear

    override func draw(_ rect: CGRect) {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = CGRect(x: CGFloat(0),
                                y: CGFloat(0),
                                width: superview!.frame.size.width,
                                height: superview!.frame.size.height)
        gradient.colors = [startColor.cgColor, endColor.cgColor]
        gradient.zPosition = -1
        layer.addSublayer(gradient)
    }
}

enter image description here

enter image description here