在 UITableviewcell 中设置水平渐变 swift

set horizontal gradient in UITableviewcell swift

我想在每个单元格上创建一个从左到右的水平渐变 我使用 CAGradientLayey 创建自定义层并将该层添加到 tableview 单元格

这是我在 swift

中的代码
  func gradient(frame:CGRect) -> CAGradientLayer {
    let layer = CAGradientLayer()
    layer.frame = frame
    print(frame)
    layer.startPoint = CGPointMake(0,0.5)
    layer.endPoint = CGPointMake(1,0.5)
    layer.colors = [ UIColor.redColor().CGColor,UIColor.blueColor().CGColor]
    return layer
}

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
    forRowAtIndexPath indexPath: NSIndexPath) {
        cell.layer.addSublayer(gradient(cell.frame))
           cell.textLabel?.textColor = UIColor(red:0, green:0.102, blue: 0.2, alpha: 1)

}

但是渐变并没有覆盖所有tableview单元格,它在渐变单元格和普通单元格背景颜色之间切换,看起来渐变完全覆盖了单元格文本。我不知道我做错了什么

有什么建议吗?谢谢

不使用 frame,而是使用单元格的 bounds,还有索引 0 处的 insertSublayer,因此它会位于包括标签在内的所有其他层之后

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
    forRowAtIndexPath indexPath: NSIndexPath) {
        cell.layer.insertSublayer(gradient(cell.bounds), atIndex:0)
        cell.backgroundColor = UIColor.clearColor()
        cell.textLabel?.textColor = UIColor(red:0, green:0.102, blue: 0.2, alpha: 1)            
}