向表视图添加渐变层

6

我一直在尝试找出如何向tableView添加渐变层的方法,已经尝试了很多不同的方法,但无论我做多少bringSubviews或sendSubviews,都无法显示表格视图单元格。

let gradientLayer = CAGradientLayer()

gradientLayer.frame = view.bounds

gradientLayer.colors = [UIColor(red: 125/255.0, green: 125/255.0, blue: 125/255.0, alpha: 1.0).cgColor, UIColor(red: 125/255.0, green: 125/255.0, blue: 255/255.0, alpha: 1.0).cgColor]

gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)

tableView.layer.addSublayer(gradientLayer)

无论我如何使用bring subviews和send subviews的组合,我总是遇到这个问题,单元格无法置于最前面。

enter image description here

有人知道如何修复这个问题,或者用另一种方式实现我想要做的事情吗,以使其正常工作吗?

非常感谢任何帮助。

2个回答

8
创建背景视图并将其分配给 TableView
func setGradientToTableView(tableView: UITableView, _ 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

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

还可以清除 TableView 单元格的颜色:

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.clearColor()
}

在Swift 4中,应该是backgroundView.layer.insertSublayer(gradientLayer, at: 0)。另外不要忘记,如果tableView的布局发生变化(旋转等),则渐变层将不会跟随它。您需要重写viewDidLayoutSubviews并在那里更新图层。否则,这是一个很好的解决方案,所以点个赞。 - Upholder Of Truth
可能是约束问题。请正确设置约束。 - AGM Tazim
@AGMTazim,这不是一个约束问题,因为梯度层的大小取决于我在运行项目时在Storyboard中选择的设备以及方向。我该如何解决这个问题? - D-A UK
正如我之前所说,这是因为渐变层的框架只设置一次,因此如果表视图的布局发生更改,则渐变层不会更改。为了解决这个问题,您需要将backgroundView的定义移动到类实例变量中,然后重写viewDidLayoutSubviews并添加此行backgroundView.layer.sublayers![0].frame = tableView.bounds。这样,当布局更改时,渐变层框架也将被更新。 - Upholder Of Truth
这两个都不能解决问题。背景视图的框架并不是问题,因为它与表视图保持相同,这是通过将其设置为表视图的背景来实现的。问题在于gradientLayer的框架从未被更新,因此您需要在viewDidLayoutSubviews中修复它。 - Upholder Of Truth
显示剩余7条评论

1

@AGM Tazim

感谢您提供的代码片段。我稍微调整了一下,以适应升级后的Swift语言中的'cGColor',并指定了渐变的起始和结束点。

希望这对任何想要使其更加可定制化的人有所帮助

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

    let gradientBackgroundColors = [topColor.cgColor, bottomColor.cgColor]


    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = gradientBackgroundColors
    gradientLayer.locations = [0.0,1.0]
    gradientLayer.startPoint = CGPoint(x: 0, y: 0)
    gradientLayer.endPoint = CGPoint(x: 0, y: 1)
    gradientLayer.frame = tableView.bounds
    let backgroundView = UIView(frame: tableView.bounds)
    backgroundView.layer.insertSublayer(gradientLayer, at: 0)
    tableView.backgroundView = backgroundView
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接