Why gradient doesn't cover the whole width of the view

后端 未结 4 705
孤街浪徒
孤街浪徒 2021-01-05 19:44

I\'m trying to apply a gradient to a view which is constraint to the top, left and right of the main screen but for some reason the gradient doesn\'t cover the whole width o

4条回答
  •  [愿得一人]
    2021-01-05 20:22

    You can turn it to a UIView. So it will resize automatically and can be seen directly in the Storyboard:

    @IBDesignable
    final class GradientView: UIView {
    
        @IBInspectable var firstColor: UIColor = .clear { didSet { updateView() } }
        @IBInspectable var secondColor: UIColor = .clear { didSet { updateView() } }
    
        @IBInspectable var startPoint: CGPoint = CGPoint(x: 0, y: 0) { didSet { updateView() } }
        @IBInspectable var endPoint: CGPoint = CGPoint(x: 1, y: 1) { didSet { updateView() } }
    
        override class var layerClass: AnyClass { get { CAGradientLayer.self } }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            updateView()
            layer.frame = bounds
        }
    
        private func updateView() {
            let layer = self.layer as! CAGradientLayer
            layer.colors = [firstColor, secondColor].map {$0.cgColor}
            layer.startPoint = startPoint
            layer.endPoint = endPoint
        }
    }
    

提交回复
热议问题