IOS fades with black at the top of UIImageView

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

I reviewed some answers, such as, but no one works.

In tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) I 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 do not see the gradient and is no different from when I delete the gradient code. Is my gradient below the image?

If I replace the line imageView.layer.insertSublayer(gradient, atIndex: 0) with imageView.layer.mask = gradient , then my cells will be empty and white (there is no image anymore).

+7
ios swift uiimageview cagradientlayer
source share
3 answers

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

 gradient.colors = [UIColor.blackColor().CGColor, UIColor.clearColor().CGColor] 
+8
source share

I forgot how the array of layers is ordered. However, you should simply add your gradient layer on top of the image level using addSubLayer and not insertSublayer: atIndex: you want the gradient layer on top of another layer so that the opaque parts display the image.

+3
source share

Swift 3.0 requires a few small tweaks:

  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) 
+2
source share

All Articles