在UITableView后面设置渐变
我创build了一个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))
但我得到的是这样的:
您需要创build背景视图并将其分配给单元格:
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() }