我在我的視圖控制器上插入了一個表視圖,我想知道如何給表格視圖中的單元格添加漸變背景?我可以單獨編輯每個單元,爲每個單元賦予不同的顏色漸變背景嗎?例如,每個單元格都在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.
}
}
子類'UITableViewCell'並設定通過梯度層的背景。 – vadian
是否需要爲每個單元格設置漸變?只是爲背景設置一個漸變顏色,它會在每個單元格中產生相同的效果根據我的觀點,如果您在每個單元格中提供漸變,則可能會滯後 –