在UITableView后面设置渐变 [英] Set gradient behind UITableView

查看:104
本文介绍了在UITableView后面设置渐变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a tableViewController where I'm calling this function:

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

但我得到的是:

推荐答案

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

You need to create background view and assign it to cell:

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 背景颜色以清除颜色:

Also don't forget to set UITableViewCell background color to clear color:

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

这篇关于在UITableView后面设置渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆