在UITableView后面设置渐变

And*_*ann 13 gradient uitableview ios swift

我创建了一个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)

}
Run Code Online (Sandbox Code Playgroud)

有:

setTableViewBackgroundGradient(self, UIColor(0xF47434), UIColor(0xEE3965))
Run Code Online (Sandbox Code Playgroud)

但我得到的是这个:

在此输入图像描述

Ser*_*nov 36

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

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
}
Run Code Online (Sandbox Code Playgroud)

另外不要忘记设置UITableViewCell背景颜色以清除颜色:

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.clearColor()
}
Run Code Online (Sandbox Code Playgroud)