Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

slooksterPSV

macrumors 68040
Original poster
Apr 17, 2004
3,543
305
Nowheresville
I’ve been learning Swift and iOS programming and one of the challenges is to add a CAGradientLayer to the view.

I’ve created sub views and get colors to show up but I can’t get CAGradientLayer to appear on my view. In view did load I can get flat color views but not gradients. What am I doing wrong? Am I not adding it to the view properly?

Thanks.
 
Last edited:

slooksterPSV

macrumors 68040
Original poster
Apr 17, 2004
3,543
305
Nowheresville
Really? The reason it wasn't working is because I wasn't using the cgColor for the color values. Wow, okay, good to know.

It's fixed now.

Swift:
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        let newView = UIView()
        newView.frame = view.frame
        
        let gradient = CAGradientLayer()
        gradient.frame = view.frame
        gradient.colors = [UIColor.blue.cgColor, UIColor.yellow.cgColor, UIColor.red.cgColor]
        newView.layer.addSublayer(gradient)
        
        view.insertSubview(newView, at: 0)
    }
}
 

casperes1996

macrumors 604
Jan 26, 2014
7,486
5,650
Horsens, Denmark
Instead of doing .cgColor you could also just use the CGColor class directly. - UIColor is built on top of CGColor, so CGColor has no idea that UIColor exists, but UIColor knows about CGColor since CG is below it. CgColors are in a way more primitive types
 
  • Like
Reactions: slooksterPSV
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.