0

The following code seems to work using Objective-C however its Swift version doesn't work.

I have tried the following:

  • Add the gradient inside the collection view cell
  • Add the gradient in the viewController
  • Use UIColor & CGColor
  • Use insertSubLayer

    var mGradient = CAGradientLayer()
    mGradient.frame = favoriteCell.mImageView.bounds
    var colors = [CGColor]()
    colors.append(UIColor(red: 0, green: 0, blue: 0, alpha: 1).CGColor)
    colors.append(UIColor(red: 0, green: 0, blue: 0, alpha: 0).CGColor)
    
    mGradient.startPoint = CGPointMake(0.1, 0.5)
    mGradient.endPoint = CGPointMake(0.9, 0.5)
    
    favoriteCell.mImageView.layer.addSublayer(mGradient)
    

3 Answers 3

3

Swift 3

let mGradient = CAGradientLayer()
mGradient.frame = favoriteCell.mImageView.bounds
var colors = [CGColor]()
colors.append(UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor)
colors.append(UIColor(red: 0, green: 0, blue: 0, alpha: 0).cgColor)

mGradient.startPoint = CGPoint(x: 0.1, y: 0.5)
mGradient.endPoint = CGPoint(x: 0.9, y: 0.5)
mGradient.colors = colors

favoriteCell.mImageView.layer.addSublayer(mGradient)
Sign up to request clarification or add additional context in comments.

Comments

2

You need to set set the colors of the gradient

mGradient.colors = colors

2 Comments

I tried the OPs code combined with setting the colors - it works fine and if it won't show up for you your issue is maybe that your imageView has a zero frame or is nil or that it has other child layers
This was the problem. Thanks
1

Try this one:

var mGradient : CAGradientLayer = CAGradientLayer()
mGradient.frame = favoriteCell.mImageView.bounds
mGradient.frame.origin = CGPointMake(0.0,0.0)

var colors = [CGColor]()
colors.append(UIColor(red: 0, green: 0, blue: 0, alpha: 1).CGColor)
colors.append(UIColor(red: 0, green: 0, blue: 0, alpha: 0).CGColor)

mGradient.locations = [0.0 , 1.0]
mGradient.startPoint = CGPointMake(0.1, 0.5)
mGradient.endPoint = CGPointMake(0.9, 0.5)
mGradient.frame = CGRect(x: 0.0, y: 0.0, width: favoriteCell.mImageView.frame.size.width, height: favoriteCell.mImageView.frame.size.height)

favoriteCell.mImageView.layer.insertSublayer(mGradient, atIndex: 0)

1 Comment

Hmmm this worked for me in iOS 8. Maybe check out this: github.com/agibson73/Gradients/tree/master/Gradients

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.