UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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() {
        super.viewDidLoad()

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

        //view.layer.addSublayer(gradientLayer)
        //print(view.layer.zPosition)
        //print(gradientLayer.zPosition)
        view.layer.insertSublayer(gradientLayer, at: 0)
    }

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

3      

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.

4      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.