Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set horizontal gradient in UITableviewcell swift

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

like image 395
sin90 Avatar asked Jan 04 '16 14:01

sin90


1 Answers

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)            
}
like image 115
Mohammed Shakeer Avatar answered Oct 28 '22 03:10

Mohammed Shakeer