Imran Imran - 12 days ago 5
iOS Question

iOS fade to black at top of UIImageView

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).

Answer

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

gradient.colors = [UIColor.blackColor().CGColor, UIColor.clearColor().CGColor]
Comments