NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

SOLVED: Difference between insertSublayer and addSublayer

Forums > iOS

I am creating a CAGradientLayer and then adding it to my view.layer, but this makes the CAGradientLayer appear on top of my UIButtons and UILabels from the storyboard. I came across a solution which is to use the method insertSublayer at zPosition 0.

But I don't understand why there would be a difference, since after calling addSublayer, if I check the zPosition of my new sublayer it says 0, why does addSublayer positions it on top of everything else? From the documentation I can tell no difference except for the fact that with insertSublayer I can determine the layer's exact position.

Thanks in advance.

  let gradientLayer = CAGradientLayer()

    override func viewDidLoad() {

        gradientLayer.colors = [, UIColor.gray.cgColor]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 1)

        view.layer.insertSublayer(gradientLayer, at: 0)

    override func viewWillLayoutSubviews() {
        gradientLayer.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)


Answering my own question, I found out the second parameter in insertSublayer has nothing to with the zPosition but actually refers to the index of [CALayer]. The index 0 corresponds to the layer on the back, the very last one. And the last index represents the layer on the front. So addSublayer adds the layer to the end of the array which makes it appear on top of all layers.


Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

Not logged in

Log in

Link copied to your pasteboard.