Reputation: 477
I'm making a weather app and for showing maximum and minimum temperature of the day, I'm using a UIView that's corners I've rounded by using .layer.cornerRadius. Now I want to add a gradient layer with different colors (symbolizing temperature), but the gradientLayer doesn't appear. Here's my viewDidLoad(), the views name is currentMinMaxTemperatureView:
let gradientLayer = CAGradientLayer()
gradientLayer.frame = currentMinMaxTemperatureView.bounds
gradientLayer.cornerRadius = currentMinMaxTemperatureView.cornerRadius
gradientLayer.colors = [UIColor.blue, UIColor.yellow, UIColor.red]
currentMinMaxTemperatureView.layer.addSublayer(gradientLayer)
Why doesn't it appear? When running this, my view looks like this:
Upvotes: 1
Views: 1377
Reputation: 160
There are a couple of problems with your code:
First, as @archLucifer mentioned, CAGradientLayer
expects CGColor
, not UIColor
.
Simply convert your colours like so:
[UIColor.blue.cgColor, UIColor.yellow.cgColor, UIColor.red.cgColor]
Second, you want to make sure you add your gradient after your currentMinMaxTemperatureView
is added to the superview. Otherwise, its bounds
will be nil
.
Try adding the gradient later in your UIViewController
lifecycle, like ViewDidLayoutSubviews()
Upvotes: 5
Reputation: 389
Try the following
gradientLayer.colors = [UIColor.blue.cgColour, UIColor.yellow.cgColour, UIColor.red.cgColour]
Upvotes: 3