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.
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()
}
@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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With