我创建了一个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))
但我得到的是:
答案 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()
}