2015-05-03 4 views
9

Я создал tableViewController, где я звоню эту функцию:Установить градиент позади 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) 

} 

с:

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

, но все, что я получаю это:

enter image description here

ответ

23

Вам необходимо создать фоновый просмотр и назначить его ячейке:

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 
} 

Также не забудьте установить цвет фона UITableViewCell очистить цвет:

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

Yay, вы спасли мой день, спасибо так много! –

+0

очень хорошее решение, спасибо –

+0

Цвет ячейки также можно установить в раскадровке. –

Смежные вопросы