在UITableView后面设置渐变

时间:2015-05-03 18:56:04

标签: ios uitableview swift gradient

我创建了一个tableViewController,我在这里调用了这个函数:

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

1 个答案:

答案 0 :(得分:34)

您需要创建背景视图并将其分配给单元格:

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()
}