Reputation: 1288
I have been adding CAGradient layers to cells using this code:
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as myCell
cell.mImageView.image = UIImage(named: scripts[indexPath.row].thumbnailImage)
let gradientLayer = CAGradientLayer()
if(cell.layer.sublayers.count == 2){ //This is to stop stacking gradient layers
gradientLayer.colors = [UIColor.clearColor().CGColor, UIColor.blackColor().CGColor]
gradientLayer.locations = [0.6, 1.0]
gradientLayer.frame = cell.bounds
cell.layer.insertSublayer(gradientLayer, below: cell.mImageView.layer)
}
This is from within the tableView(_:cellForRowAtIndexPath) method of my CustomTableViewController class.
I have a myCell
class that I would much rather use to perform the gradient layout, but I cannot use this code or the cell
object from within the awakeFromNib()
method.
How can I insert this CAGradientLayer from within the awakeFromNib
(or init()
) method of the myCell class? The cell also contains a label and I would like to insert it beneath the label as well.
Upvotes: 0
Views: 1651
Reputation: 104082
I don't know why you would get that error. I tried a slight modification of your code (in the cell class), and it worked ok. Here it is,
class RDTableViewCell: UITableViewCell {
@IBOutlet var mImageView: UIImageView!
override func didMoveToSuperview() {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.clearColor().CGColor, UIColor.blackColor().CGColor]
gradientLayer.locations = [0.6, 1.0]
gradientLayer.frame = self.bounds
self.layer.insertSublayer(gradientLayer, below: self.mImageView.layer)
}
}
I assumed that you want the gradient at the bottom of the cell, and that did not happen with my cells (which had a height of 70) if I put the code in awakeFromNib.
Upvotes: 4