D-A UK
D-A UK

Reputation: 1174

Adding gradient layer to tableview

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:

enter image description here

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.

Upvotes: 6

Views: 1940

Answers (2)

ivan ramirez
ivan ramirez

Reputation: 71

@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
}

Upvotes: 1

AGM Tazim
AGM Tazim

Reputation: 2217

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()
}

Upvotes: 8

Related Questions