我在 View Controller 上插入了一个表格 View ,我想知道如何为表格 View 中的单元格提供渐变背景?我可以单独编辑每个单元格,为每个单元格赋予不同的颜色渐变背景吗?例如,每个单元格都在 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/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) | Powered by Discuz! X3.4 |