TableView背景渐变故障

问题描述 投票:1回答:1

我有一个用于表视图的渐变图层集,使用以下代码:

func setGradientToTableView(_ topColor:UIColor, _ bottomColor:UIColor) {

    let gradientBackgroundColors = [topColor.cgColor, bottomColor.cgColor]
    let gradientLocations = [0.0,1.0]

    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = gradientBackgroundColors
    gradientLayer.locations = gradientLocations as [NSNumber]

    gradientLayer.frame = tableView.bounds
    let backgroundView = UIView(frame: tableView.bounds)
    backgroundView.layer.insertSublayer(gradientLayer, at: 0)
    tableView.backgroundView = backgroundView

}

还有这个:

setGradientToTableView(UIColor(red: 125/255.0, green: 125/255.0, blue: 125/255.0, alpha: 1.0), UIColor(red: 125/255.0, green: 125/255.0, blue: 0/255.0, alpha: 1.0)).

当我运行应用程序时,问题就出现了。渐变图层将是故事板中选定的设备和方向的表视图的大小。

有谁知道如何解决这一问题? - 顺便说一句,我对表视图的约束是导航栏底部,前导,尾随和安全区域底部

编辑:这是一个截图

enter image description here

ios swift uitableview cagradientlayer
1个回答
4
投票

可能问题是您在viewDidLoad()方法中设置了渐变,其中尚未绘制表视图,其框架是XIB / storyboard的默认框架。你应该在didLayoutSubviews()中这样称呼:

var gradientLayer: CAGradientLayer?
func didLayoutSubviews() {
    if (gradientLayer == nil) {
        setGradientToTableView(UIColor(red: 125/255.0, green: 125/255.0, blue: 125/255.0, alpha: 1.0), UIColor(red: 125/255.0, green: 125/255.0, blue: 0/255.0, alpha: 1.0))
    }
}

保持对类中渐变图层的引用,以确保只设置一次渐变,因为多次调用didLayoutSubviews

© www.soinside.com 2019 - 2024. All rights reserved.