Extra CALayer's subLayers in iOS

1k views Asked by At

I have created a new single view project written in swift and print self.view.layer.sublayers.count. The number is 2, but I haven't add any layer or UIView.

override func viewDidLoad() {
    super.viewDidLoad()
    println(self.view.layer.sublayers.count)
    // Do any additional setup after loading the view, typically from a nib.
}

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

I wonder what the extra two layers are.

1

There are 1 answers

0
Sulthan On BEST ANSWER

Every UIView is backed up by a CALayer, the view hierarchy and the layer hierarchy are connected to each other.

If you print out the subviews, you will see that the view has two subviews of type _UILayoutGuide which represent the controller's topLayoutGuide and bottomLayoutGuide. Every subview has a layer so that's your 2 sublayers.

To prove it:

override func viewDidLoad() {
    super.viewDidLoad()

    print("Top layout guide layer: \((self.topLayoutGuide as! UIView).layer)");
    print("Bottom layout guide layer: \((self.bottomLayoutGuide as! UIView).layer)");
    print("Sublayers: \(self.view.layer.sublayers)");
}

prints:

Top layout guide layer: <CALayer: 0x7fef8ac28140>
Bottom layout guide layer: <CALayer: 0x7fef8ac27bc0>
Sublayers: Optional([<CALayer: 0x7fef8ac28140>, <CALayer: 0x7fef8ac27bc0>])