如何使细胞具有渐变背景? [英] How to make cells have a gradient background?
本文介绍了如何使细胞具有渐变背景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在视图控制器上插入了一个表格视图,我想知道如何为表格视图中的单元格提供渐变背景?我可以分别编辑每个单元格以使其具有不同的颜色渐变背景吗?例如,每个单元格都在 trainingLevels
数组中的索引后面标记,我该如何确定每个单元格具有不同的颜色渐变背景?
I have inserted a table view on my view controller and I was wondering how can I give the cells in the table view a gradient background? Can I edit each cell individually to give it a different color gradient background for each cell? For example, each cell is labeled after an index in the trainingLevels
array, how could I make to where each has a different color gradient background?
这是我的代码:
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.
}
}
推荐答案
您可以创建UIView的扩展:
You can create extension of 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)
}
这篇关于如何使细胞具有渐变背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文