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

前端 未结 9 1153
终归单人心
终归单人心 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:55

    Based on etayluz answer I changed the code a little bit by taking the layerClass property of a UIView into account, so you do not need a separate layer as a sublayer.

    I think it is much cleaner and it also works with live updates in the Interface Builder.

    @IBDesignable final class GradientView: UIView {
    
        @IBInspectable var startColor: UIColor = UIColor.red
        @IBInspectable var endColor: UIColor = UIColor.blue
    
        override class var layerClass: AnyClass {
            get {
                return CAGradientLayer.self
            }
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupGradient()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setupGradient()
        }
    
        private func setupGradient() {
            let gradient = self.layer as! CAGradientLayer
            gradient.colors = [startColor.cgColor, endColor.cgColor]
        }
    
    }
    

提交回复
热议问题