我在我的 View Controller 上插入了一个 TableView ,我想知道如何为 TableView 中的单元格提供渐变背景?我可以单独编辑每个单元格,为每个单元格提供不同的颜色渐变背景吗?例如,每个单元格都在 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.
}
}
最佳答案
您可以创建 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)
}
关于swift - 如何使单元格具有渐变背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51448584/