2015-05-03 12 views
9

Ho creato un tableViewController dove sto chiamando questa funzione:Set gradiente dietro UITableView

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) 

} 

con:

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

ma tutto quello che ottiene è questo:

enter image description here

risposta

23

È necessario creare una vista di sfondo e assegnarla alla cella:

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 
} 

Inoltre, non dimenticare di impostare il colore di sfondo per cancellare UITableViewCell colore:

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 
    cell.backgroundColor = UIColor.clearColor() 
} 
+0

Yay, mi hai salvato la giornata, grazie mille! –

+0

soluzione molto bella, grazie –

+0

il colore della cella può anche essere impostato nello storyboard. –