Search code examples
iosswiftuitableviewcagradientlayer

Swift Alternating UITableViewCell gradient color


I used to have this code in the tableView willDisplay cell method, but it did not accurate alternate the colors - it almost did but still messed up sometimes with 1 or 2 that were the same color and I was not sure.

I found somethings that suggested calling all the methods in the awakeFromNib method in my custom UITableViewCell class so I moved everything like so:

class SectionTableViewCell: UITableViewCell {
    @IBOutlet weak var lblName: UILabel!
    @IBOutlet weak var lblValue: UILabel!

    var cellGradient_1: CAGradientLayer = CAGradientLayer()
    var cellGradient_2: CAGradientLayer = CAGradientLayer()

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        self.layer.insertSublayer(cellGradient_1, at: 0)
        self.layer.insertSublayer(cellGradient_2, at: 0)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        cellGradient_1.frame = self.bounds
        cellGradient_2.frame = self.bounds
    }

}

Now, in my tableView cellForRowAt I make this check:

let cell = tableView.dequeueReusableCell(withIdentifier: "Section", for: indexPath) as! SectionTableViewCell
if (indexPath.row%2 == 0) {
    cell.cellGradient_1.colors = theme.childColor_1 //Some gradient color
}
else{
    cell.cellGradient_2.colors = theme.childColor_2 //Some gradient color
}

They are all the first color now with 1 near the bottom being the second color. Am I doing something wrong with the nib? Is there a different way to set the colors of the gradients? Any help will be greatly appreciated.

Edit: It looks like it works on initial load, but as soon as the table is reloaded or scrolling happens all the cell's gradients change to the initial except 2 or 3.


Solution

  • You use two layers and the first layer covers the second layer.
    To solve this just remove second layer and change your code in tableView cellForRowAt to:

    let cell = tableView.dequeueReusableCell(withIdentifier: "Section", for: indexPath) as! SectionTableViewCell
    if (indexPath.row%2 == 0) {
        cell.cellGradient_1.colors = theme.childColor_1 //Some gradient color
    }
    else{
        cell.cellGradient_1.colors = theme.childColor_2 //Some gradient color
    }
    

    (I replaced cell.cellGradient_2 with cell.cellGradient_1)