2016-01-04 29 views
7

Voglio creare un gradiente orizzontale da sinistra a destra su ogni cella Io uso CAGradientLayey per creare un livello personalizzato e aggiungere questo strato di cellule Tableviewset gradiente orizzontale in UITableViewCell rapida

Questo è il mio codice 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) 

} 

Ma il gradiente non copre tutta la cella tableview, passa da cella a gradiente a colore di sfondo cella normale e sembra che il gradiente sovrapponga completamente il testo della cella. Non so cosa sto facendo male

Qualche suggerimento? Grazie

risposta

5

Invece di utilizzare frame, utilizzare bounds della cella, anche insertSublayer di indice 0, quindi si arriverà dietro a tutti gli altri livelli tra cui l'etichetta

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

che ha fatto, ma il testo della cella è ancora mancante . Qualche suggerimento? grazie – sin90

+0

Questo ha fatto il lavoro Grazie! – sin90