2017-08-05 31 views
1

我在我的視圖控制器上插入了一個表視圖,我想知道如何給表格視圖中的單元格添加漸變背景?我可以單獨編輯每個單元,爲每個單元賦予不同的顏色漸變背景嗎?例如,每個單元格都在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

是否需要爲每個單元格設置漸變?只是爲背景設置一個漸變顏色,它會在每個單元格中產生相同的效果根據我的觀點,如果您在每個單元格中提供漸變,則可能會滯後 –

回答

1

您需要首先創建漸變,然後插入子層的細胞像下面。

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中不可用 –

0

您可以創建的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) 
}