Reputation: 1039
I have a table with custom table view cells. each table view cell has a background image plus some text on top of the image. I would like to add a gradient above the image view so that the text above the image is more easily readable.
Where is the CORRECT place to add this gradient?
I am currently adding this in cellForRowAtIndexPath, i'm pasting the code below.. the array cellShown keeps track of whether this cell was shown or not.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("AirportPlaceListTableViewCell") as! AirportPlaceListTableViewCell
cell.titleLabel.text = tableData[indexPath.row] as? String
let imageName = tableImageData[indexPath.row] as? String
let image = UIImage(named: imageName!)
cell.placeImageView.image = TripnaryHelper.imageWithImage(image, scaledToSize: CGSizeMake(320, 320))
if cellShown[indexPath.row] == false
{
let gradient = CAGradientLayer.init()
gradient.frame = cell.bounds
let bottomColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
gradient.colors = [UIColor.clearColor().CGColor, bottomColor.CGColor]
gradient.startPoint = CGPoint(x: 0, y: 0.66)
gradient.endPoint = CGPoint(x: 0, y: 1.0)
cell.placeImageView.layer .addSublayer(gradient)
cellShown[indexPath.row] = true
}
return cell
}
what is happening here is that when the cells get reused, the gradient is getting added again. so my question is - how do I check for that? - or, is there another place to add this gradient for my custom table view cell class?
Upvotes: 2
Views: 338
Reputation: 4646
You should add the CAGradientLayer
in your custom cell's (AirportPlaceListTableViewCell
) overridden initialization method:
init(style style: UITableViewCellStyle, reuseIdentifier reuseIdentifier: String?)
However, if you have built your custom cell in a xib
, then you'll want to add the CAGradientLayer
after the xib
has been loaded. In which case you can do it in AirportPlaceListTableViewCell
's:
func awakeFromNib()
Upvotes: 2