I want to create a horizontal gradient from left to right on each cell I use CAGradientLayey to create a custom layer and add this layer to tableview cell
This is my code in swift
func gradient(frame:CGRect) -> CAGradientLayer {
let layer = CAGradientLayer()
layer.frame = frame
print(frame)
layer.startPoint = CGPointMake(0,0.5)
layer.endPoint = CGPointMake(1,0.5)
layer.colors = [ UIColor.redColor().CGColor,UIColor.blueColor().CGColor]
return layer
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath) {
cell.layer.addSublayer(gradient(cell.frame))
cell.textLabel?.textColor = UIColor(red:0, green:0.102, blue: 0.2, alpha: 1)
}
But the gradient is not cover all tableview cell, it switches between gradient cell and normal cell background color and it seems like the gradient overlay the cell text completely. I don't know what I'm doing wrong
Any suggestion? Thank you
Instead of using frame
, use bounds
of the cell, Also insertSublayer
at index 0, so it will come behind all other layers including your label
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath) {
cell.layer.insertSublayer(gradient(cell.bounds), atIndex:0)
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.textColor = UIColor(red:0, green:0.102, blue: 0.2, alpha: 1)
}
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