9

I have a UITableView where my cell backgroundView is a UIImageView. I would like top of each image to fade to black so I can overlay some white text.

I have looked at some answers like this, but none seem to be working.

In tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) I have tried:

var imageView = UIImageView(image: image)

var gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = imageView.frame
gradient.colors = [UIColor.blackColor(), UIColor.clearColor()]
gradient.locations = [0.0, 0.1]
imageView.layer.insertSublayer(gradient, atIndex: 0)

cell!.backgroundView = imageView

But I see no gradient and no difference from when I remove the gradient code. Is my gradient sitting under the image?

If I replace the line imageView.layer.insertSublayer(gradient, atIndex: 0) with imageView.layer.mask = gradient then my cells are just blank and white (no image anymore).

Community
  • 1
  • 1
Imran
  • 12,950
  • 8
  • 64
  • 79

3 Answers3

9

In your gradient.colors you need to have array of CGColor, so:

gradient.colors = [UIColor.blackColor().CGColor, UIColor.clearColor().CGColor]
Imran
  • 12,950
  • 8
  • 64
  • 79
libec
  • 1,555
  • 1
  • 10
  • 19
3

I forget how the layers array is ordered. However, you should just add your gradient layer on top of your image view's layer using addSubLayer, not insertSublayer:atIndex: You want the gradient layer on top of the other layer so that it's non-opaque parts cover the image view.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Both work for me with the CGColor fix from the accepted answer, but yes, addSubLayer is definitely more straightforward. – Imran Aug 06 '15 at 17:04
3

For Swift 3.0, some slight tweaks required:

    let gradient: CAGradientLayer = CAGradientLayer()
    gradient.frame = imageView.frame
    gradient.colors = [UIColor.black.cgColor, UIColor.clear.cgColor]
    gradient.locations = [0.0, 0.1]
    imageView.layer.insertSublayer(gradient, at: 0)
David West
  • 1,550
  • 1
  • 18
  • 31