Why gradient layer in UITableViewCell not cover entire frame?

蓝咒 提交于 2019-12-05 12:54:39

You should use view's boundsinstead of frame, because your layer is inside of the view, and the frame may have an offset.

The layout of the view is changed after awakeFromNib. So you should resize the layer in layoutSubviews of the view. For this create a property gradient and:

let gradient: CAGradientLayer = CAGradientLayer()

override func awakeFromNib() {
    ...
    let colors = [
                UIColor(red: 33/255.0, green: 33/255.0, blue: 33/255.0, alpha: 1.0).cgColor,
                UIColor(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1.0).cgColor]
    gradient.frame = bounds
    gradient.colors = colors
    gradientView.layer.insertSublayer(gradient, at: 0) 
    ...
}

override func layoutSubviews() {
    super.layoutSubviews()
    gradient.frame = bounds
}

EDIT: An alternative is a custom view with own layer class:

public class GradientLayer: UIView {
    @IBInspectable var startColor: UIColor! = UIColor(red: 33/255.0, green: 33/255.0, blue: 33/255.0, alpha: 1.0)
    @IBInspectable var endColor: UIColor! = UIColor(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1.0)

    override class var layerClass : AnyClass {
        return CAGradientLayer.self
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        let colors = [ startColor.cgColor, endColor.cgColor ]
        if let gradient = self.layer as? CAGradientLayer {
            gradient.colors = colors
        }
    }
}

This is more elegant, because you can replace the static colors with IB inspectables, and you have a reusable component view.

 override func layoutSubviews() {
        super.layoutSubviews()

        if let gradient = baseView.layer.sublayers?[0] as? CAGradientLayer {
            gradient.frame = self.bounds
        }
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!