2016-01-04 50 views
7

我想創建一個水平漸變從左至右在每個單元 我用CAGradientLayey創建自定義層,這層添加到tableview中細胞設置水平梯度迅速

這是我在迅速

代碼
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單元格,它在漸變單元格和正常單元格背景色之間切換,看起來像漸變疊加單元格文本。我不知道我在做什麼錯

有什麼建議嗎?謝謝

回答

5

而不是使用frame的,使用電池的bounds,也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)    
} 
+0

這做到了,但單元格文本,至今下落不明。任何建議?謝謝 – sin90

+0

這樣做的工作謝謝! – sin90