1

I am fairly new to Swift and XCode. I have just learnt how to create a gradient on a Navigation Controller from a tutorial video, however in the video I watch the guy used a UIColor and I want to use a CGColor, so I used this code:

class func gradientLayerForBounds(bounds: CGRect) -> CAGradientLayer {
  let layer = CAGradientLayer()
  let topColor = UIColor(red: 244, green: 45, blue: 78, alpha: 100)
  let bottomColor = UIColor(red: 245, green: 67, blue: 58, alpha: 100)

  layer.bounds = bounds
  layer.colors = [topColor.CGColor, bottomColor.CGColor]

  return layer
}

However when I build and run the project, nothing appears, I get no error or warning the Debug box. Hope someone can help me out!

1 Answer 1

1

When using custom colors you need to divide the color by 255 e.g. UIColor(red: 244/255, green: 45/255, blue: 78/255, alpha: 100).

It appears you haven't done that, so I would recommend trying:

let topColor = UIColor(red: 244/255, green: 45/255, blue: 78/255, alpha: 100)
let bottomColor = UIColor(red: 245/255, green: 67/255, blue: 58/255, alpha: 100)

That should solve your problem.

Sign up to request clarification or add additional context in comments.

4 Comments

I've just tried it and not it works! Thanks ever so much for your help. Much appreciated
@TimSmith So it works? I think you mean 'now' instead of 'not'. No problem, happy to help. I just recommend searching the internet before coming to SO.
Also @TimSmith Could you accept the answer if it works (-:
Yes I will accept the answer as it has solved my problem

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.