如何让单元格具有渐变背景?

问题描述:

我在我的视图控制器上插入了一个表视图,我想知道如何给表格视图中的单元格添加渐变背景?我可以单独编辑每个单元,为每个单元赋予不同的颜色渐变背景吗?例如,每个单元格都在trainingLevels数组中的索引之后进行标记,我怎样才能使每个单元具有不同的颜色渐变背景?如何让单元格具有渐变背景?

这里是我的代码:

import UIKit 

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

var trainingLevels = ["Ball Handling", "Shooting", "Defense", "Advanced Drills", "Vertimax Drills", "Full Workouts", "BHB Products"] 


@IBOutlet weak var tableView: TableView! 


func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { 
    cell.backgroundColor = UIColor.clear 
} 

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
{ 

    return trainingLevels.count 
} 


public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{ 
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "bell") 
    cell.textLabel?.text = trainingLevels[indexPath.row] 

    //cell details 
    cell.backgroundColor = UIColor.black 
    cell.textLabel?.textColor = UIColor.white 



    return cell 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 

    tableView.delegate = self 
    tableView.dataSource = self 

    // Do any additional setup after loading the view, typically from a nib. 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 
} 
+0

子类'UITableViewCell'并设定通过梯度层的背景。 – vadian

+0

是否需要为每个单元格设置渐变?只是为背景设置一个渐变颜色,它会在每个单元格中产生相同的效果根据我的观点,如果您在每个单元格中提供渐变,则可能会滞后 –

您需要首先创建渐变,然后插入子层的细胞像下面。

func gradient(frame:CGRect) -> CAGradientLayer { 
    let layer = CAGradientLayer() 
    layer.frame = frame 
    layer.startPoint = CGPointMake(0,0.5) 
    layer.endPoint = CGPointMake(1,0.5) 
    layer.colors = [ 
    UIColor.red.cgColor,UIColor.blue.cgColor] 
    return layer 
} 

//Now on your tableViewcell do below 

cell.layer.insertSublayer(gradient(cell.bounds), atIndex:0) 
+0

我建议'cell.layer.insertSublayer(gradient(cell.bounds), atIndex:0)'行放在UITableViewCell的awakeFromNib()函数的子类中,并用'self'替换'cell'。如果该行在tableView(cellForRowAt :)函数中,它很容易导致滚动滞后。 – RPatel99

+0

如何实现用'self'替换'cell'? –

+0

也说'cgcolor'在swift中不可用 –

您可以创建的UIView的延伸:

extension UIView{ 
    func addGradientBackground(firstColor: UIColor, secondColor: UIColor){ 
     clipsToBounds = true 
     let gradientLayer = CAGradientLayer() 
     gradientLayer.colors = [firstColor.cgColor, secondColor.cgColor] 
     gradientLayer.frame = self.bounds 
     gradientLayer.startPoint = CGPoint(x: 0, y: 0) 
     gradientLayer.endPoint = CGPoint(x: 0, y: 1) 
     print(gradientLayer.frame) 
     self.layer.insertSublayer(gradientLayer, at: 0) 
    } 
} 

而且你的细胞里面简单:

override func awakeFromNib() { 
    super.awakeFromNib() 
    self.addGradientBackground(firstColor: .green, secondColor: .blue) 
}