在Swift中设置UITableviewcell的水平渐变

7

我希望在每个单元格上创建一个从左到右的水平渐变。我使用CAGradientLayer来创建自定义层,并将此层添加到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)

}

但是渐变并没有覆盖所有的表格视图单元格,它在渐变单元格和普通单元格背景颜色之间切换,似乎渐变完全覆盖了单元格文本。我不知道我做错了什么。
有什么建议吗?谢谢。
1个回答

5

使用单元格的bounds而不是frame,同时将insertSublayer插入到索引0处,这样它就会被放置在所有其他图层(包括标签)的后面。

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

搞定了,但是单元格的文本还是缺失的。有什么建议吗?谢谢。 - sin90
那做到了工作,谢谢! - sin90

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接