2015-05-03 31 views
9

Stworzyłem tableViewController gdzie dzwonię tej funkcji:Set gradientu za 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) 

} 

z:

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

ale mam to:

enter image description here

Odpowiedz

23

Musisz utworzyć widok tła i przypisać go do komórki:

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 
} 

Również nie zapomnij, aby ustawić kolor tła do UITableViewCell jasny kolor:

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

Yay, uratowałeś mój dzień, dziękuję bardzo! –

+0

bardzo ładne rozwiązanie, dziękuję –

+0

kolor komórki można również ustawić w storyboard. –