What is a CALayer (as seen in the layer
property on a UIView) and where would we use such a class?
Swift version: 5.6. All UIView subclasses have a layer property, which is responsible for drawing their contents efficiently. These layers are powered by Core Animation, which handles all the drawing and animation that UIKit requests.
A layer is a simple model class that exposes a number of properties to represents some image-based content. Every UIView is backed by a layer, so you can think of layers as the lower-level behind the scenes class behind your content.
However if you want to draw text on a CALayer object, it can be done using the drawing functions provided in NSString UIKit additions as shown below. While my code is done in the delegate's drawLayer:inContext method, the same can be used in subclass' drawInContext: method.
Embedding one view inside another creates a containment relationship between the host view (known as the superview) and the embedded view (known as the subview).
A UIView is a aggregate class. It contains "stuff" for the event responder chain, stuff for handling the view hierarchy, etc., as well as stuff regarding what to draw on the display. The CALayer of a UIView is just the stuff regarding what to draw: the image bits, the scale, transform, animation properties, etc.
The Cocoa Touch UI is drawn by compositing layers... views on top of views on top of a window. A CALayer is a layer in the composition stack which goes on top of some layers, and potentially underneath other layers. (e.g. an image in a button in a table cell in a view in a split view, etc.)
If you want to do something special with what a view draws or displays that isn't provided in the stock UIView class methods, it might be possible to do that special something by going directly to the CALayer: maybe swapping layers between views and/or images, drawing stuff off-screen, custom animations, etc.
There's lots more explained in Apple CALayer Class Reference document
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With