How to make cells have a gradient background?
Asked Answered
L

2

7

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.
}
}
Lewes answered 5/8, 2017 at 3:54 Comment(2)
Subclass UITableViewCell and set the background via a gradient layer.Capsule
is it required to set gradient for each cell ? just set a gradient color for background and it will give same effect in each of your cell According to me it may lag if you provide gradient in each cellSupernal
T
9

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)
}
Tomikotomkiel answered 5/8, 2017 at 8:1 Comment(2)
Add this line only in Xib file otherwise when cell be reload then is add multiple Gradient in cell self.addGradientBackground(firstColor: .green, secondColor: .blue)Lurlinelusa
I have an identical extension for a gradient in a uiview but I found that, depending on the screen size, the gradient either wont fill the width of the cell when used in awakeFromNib(), or fills incorrectly when used in layoutSubviews(). draw(_ rect: CGRect) seems to update properly though.Rocco
S
6

You need to create the gradient first and then insert sublayer to your cell like below.

func gradient(frame:CGRect) -> CAGradientLayer {
    let layer = CAGradientLayer()
    layer.frame = frame
    layer.startPoint = CGPointMake(0,0.5)
    layer.endPoint = CGPointMake(1,0.5)
    layer.colors = [ 
    UIColor.red.cgColor,UIColor.blue.cgColor]
    return layer
}

//Now on your tableViewcell do below

cell.layer.insertSublayer(gradient(cell.bounds), atIndex:0)

for Swift 4.0

func gradient(frame:CGRect) -> CAGradientLayer {
        let layer = CAGradientLayer()
        layer.frame = frame
        layer.startPoint = CGPoint(x: 0, y: 0.5)
        layer.endPoint = CGPoint(x: 1, y: 0.5)
        layer.colors = [
            UIColor.gray.cgColor,UIColor.cyan.cgColor]
        return layer
    }

    cell.layer.insertSublayer(gradient(frame: backgroundView.bounds), at:0)
Superficies answered 5/8, 2017 at 4:26 Comment(3)
I recommend that the cell.layer.insertSublayer(gradient(cell.bounds), atIndex:0) line is placed inside a subclass of UITableViewCell's awakeFromNib() function, and replace the cell with self. It could easily cause scrolling lag if that line is in the tableView(cellForRowAt:) function.Extrusive
How would implement replacing cell with self?Lewes
also says cgcolor is unavailable in swiftLewes

© 2022 - 2024 — McMap. All rights reserved.