本文介绍了将渐变图层添加到 tableview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图弄清楚如何向 tableView 添加渐变图层,并尝试了很多不同的方法,但我永远无法让 table view 单元格显示出来,无论有多少带来或 sendSubviews 我做.

I have been trying to figure out for quite a while now about how to add a gradient layer to the tableView, and have tried many different things, but I can never get the table view cells to show, no matter how many bringSubviews or sendSubviews I do.

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做了多少个组合,我好像总能搞定这个,cell都不会出现在前面:

No matter how many combinations of bring subviews and send subviews are done, I always seem to get this and the cells won't come to the front:

有谁知道如何解决这个问题,或者如何做我想做的事情以另一种方式使其工作?

Does anyone know how to fix this, or how to do what I want to do another way to make it work?

非常感谢任何帮助,谢谢.

Any help is much appreciated, thanks.

推荐答案

创建背景视图并将其分配给TableView:

Create background view and assign it to 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()
}

这篇关于将渐变图层添加到 tableview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 01:08