Adding gradient layer to tableview

丶灬走出姿态 提交于 2019-12-07 23:57:51

问题


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)

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.


回答1:


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
}

Also clear color of TableView cell:

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



回答2:


@AGM Tazim

Thanks for that snippet of code. I tweaked it a bit to account for the upgraded swift language for 'cGColor' and specified the start and end point of the gradient.

Hope this is helpful to anyone wanting to make it more customizable

    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
}


来源:https://stackoverflow.com/questions/48041519/adding-gradient-layer-to-tableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!