swift - 如何使单元格具有渐变背景?

标签 swift cell gradient viewcontroller

我在我的 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/

相关文章:

uiview - Swift 编译器错误 "failed with exit code 254"

html - 如何在 CSS 中指定表格填充? (表格,不是单元格填充)

python - 绘制直方图以找出图像上梯度的最大强度

c# - 沿圆形路径创建渐变画笔

ios - 如何执行条件 'executeFetchRequest' 以仅获取特定属性为 nil 的那些实体?

ios - 如何使 UIBarButtonItem 在按下时执行功能?

swift - 拆分字符串导致类型 'Any?' 的值没有成员 'components'

ios - 错误-swift-Tableview-自定义单元格

jqGrid 动态更改特定行的编辑类型

css - 将 css3 渐变与背景图像相结合