Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

swift - How to make cells have a gradient background?

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?

Here's my code:

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.
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
    }
}

And inside your cell simply:

override func awakeFromNib() {
    super.awakeFromNib()
    self.addGradientBackground(firstColor: .green, secondColor: .blue)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...