Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set gradient behind UITableView

I have created a tableViewController where I'm calling this function:

func setTableViewBackgroundGradient(sender: UITableViewController ,let topColor:UIColor, let 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 = sender.tableView.bounds
    sender.tableView.backgroundView?.layer.insertSublayer(gradientLayer, atIndex: 0)

}

with:

setTableViewBackgroundGradient(self, UIColor(0xF47434), UIColor(0xEE3965))

but all I get is this:

like image 941
André Kuhlmann Avatar asked May 03 '15 18:05

André Kuhlmann


1 Answers

You need to create background view and assign it to cell:

func setTableViewBackgroundGradient(sender: UITableViewController, _ 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 = sender.tableView.bounds
    let backgroundView = UIView(frame: sender.tableView.bounds)
    backgroundView.layer.insertSublayer(gradientLayer, atIndex: 0)
    sender.tableView.backgroundView = backgroundView
}

Also don't forget to set UITableViewCell background color to clear color:

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.clearColor()
}
like image 92
Sergey Kuryanov Avatar answered Nov 09 '22 01:11

Sergey Kuryanov