yachaka
yachaka

Reputation: 5569

Can't display a simple CAGradientLayer

I'm just trying to display a simple gradient into my view controller. This code doesn't work (view stays white).

import UIKit
import QuartzCore

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let ly = CAGradientLayer()
        ly.frame = view.bounds
        ly.colors = [UIColor.orangeColor(), UIColor.blackColor()]
        ly.locations = [0.0, 1.0]
        println(view.bounds) // (0.0, 0.0, 320.0, 568.0)

        view.layer.addSublayer(ly)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

Interestingly, if I set ly.backgroundColor to orange, the view becomes orange. We can conclude the layer is effectively on top of the view but the gradient isn't effective.

Upvotes: 2

Views: 269

Answers (1)

yachaka
yachaka

Reputation: 5569

ly.colors = [UIColor.orangeColor().CGColor, UIColor.blackColor().CGColor]

ly.colors is of type [AnyObject] but expects CGColor objects. Swift wasn't giving any errors about this because of the [AnyObject], but wasn't working because it needed [CGColor].

Upvotes: 5

Related Questions