CAGradientLayer无法正常工作

时间:2017-02-26 00:24:03

标签: ios uiview cagradientlayer

我尝试使用渐变背景创建UITableViewCell。我不明白为什么,但UITableView右侧有一个白色的空白区域。我尝试设置一个纯色,但结果没有改变。

这是我的UITableViewCell类。

;

它看起来像这样。 (蓝色是表格行) enter image description here

发生了什么事?如果我从XCode设置背景,它会显示一切正常。它只是不适合屏幕大小。

1 个答案:

答案 0 :(得分:3)

问题是单元格以一种尺寸从笔尖中出来,但随后在放入界面时调整大小。但是,您的图层比细胞大小调整更早添加,并且在调整单元格大小时,图层调整大小。因此,图层最终会以错误的大小结束。

这里的一个好方法是保留对渐变图层的引用,并在layoutSubviews覆盖中调整图层的大小:

class MyTableViewCell : UITableViewCell {

    var gl : CAGradientLayer?

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

        let gl = CAGradientLayer()
        gl.frame = self.bounds
        gl.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
        gl.zPosition = -1
        self.layer.addSublayer(gl)
        self.gl = gl
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.gl?.frame = self.bounds
    }
}

enter image description here

enter image description here

相关问题