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).
In your gradient.colors
you need to have array of CGColor
, so:
gradient.colors = [UIColor.blackColor().CGColor, UIColor.clearColor().CGColor]
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With