Adding gradient layer to tableview

送分小仙女□ 提交于 2019-12-06 05:20:24

Create background view and assign it to TableView:

func setGradientToTableView(tableView: UITableView, _ 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 = tableView.bounds
    let backgroundView = UIView(frame: tableView.bounds)
    backgroundView.layer.insertSublayer(gradientLayer, atIndex: 0)
    tableView.backgroundView = backgroundView
}

Also clear color of TableView cell:

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

@AGM Tazim

Thanks for that snippet of code. I tweaked it a bit to account for the upgraded swift language for 'cGColor' and specified the start and end point of the gradient.

Hope this is helpful to anyone wanting to make it more customizable

    func setGradientToTableView(tableView: UITableView, _ topColor:UIColor, _ bottomColor:UIColor) {

    let gradientBackgroundColors = [topColor.cgColor, bottomColor.cgColor]


    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = gradientBackgroundColors
    gradientLayer.locations = [0.0,1.0]
    gradientLayer.startPoint = CGPoint(x: 0, y: 0)
    gradientLayer.endPoint = CGPoint(x: 0, y: 1)
    gradientLayer.frame = tableView.bounds
    let backgroundView = UIView(frame: tableView.bounds)
    backgroundView.layer.insertSublayer(gradientLayer, at: 0)
    tableView.backgroundView = backgroundView
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!