ios - 向tableview添加渐变层

标签 ios swift uitableview cagradientlayer

关于如何向 tableView 添加渐变层,我已经尝试了很长一段时间,并且尝试了很多不同的方法,但是无论有多少 bringSubviews,我都无法显示 table view cells或者我做的 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

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

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

最佳答案

创建背景 View 并将其分配给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()
}

关于ios - 向tableview添加渐变层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48041519/

相关文章:

ios - NSPredicate 检查 swift 中对象类的种类

ios - indexpath.row 在我介绍部分后不断重置

ios - 如何调暗 UITableViewCell

ios - 如何过滤掉太近的坐标?

ios - UISplitViewController 主内容宽度

ios - 如何使用 Swift 从图库中选择多个视频和照片

ios - 我可以在每次调用方法时将同名的 UIImage 添加到 NSMutableArray 中吗?

swift - 自 SearchBar 实现以来 Xcode 9.4.1 TableView 问题

ios - 在 iOS8 中旋转时调整工具栏的大小

ios - 使用异步数据更新 TableViewCell