Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between a UIView and a CALayer?

Both have most of the same attributes, both support different kind of animations, both represent different data. What are the differences between a UIView and a CALayer?

like image 224
Oleg Danu Avatar asked Oct 19 '11 18:10

Oleg Danu


People also ask

What is CALayer in Swift?

An object that manages image-based content and allows you to perform animations on that content.

What is a UIView iOS?

An object that manages the content for a rectangular area on the screen.

What is the layer property on a UIView object?

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.


2 Answers

On iOS, every UIView is backed by a Core Animation CALayer, so you are dealing with CALayers when using a UIView, even though you may not realize it. Unlike NSViews on the Mac, which evolved before Core Animation existed, UIViews are intended to be lightweight wrappers around these CALayers.

As I describe in the similar question "When to use CALayer on the Mac/iPhone?", working directly with CALayers doesn't give you significant performance advantages over UIViews. One of the reasons you might want to build a user interface element with CALayers instead of UIViews is that it can be very easily ported to the Mac. UIViews are very different from NSViews, but CALayers are almost identical on the two platforms. This is why the Core Plot framework lays out its graphs using CALayers instead of other UI elements.

One thing UIViews provide over CALayers is built-in support for user interaction. They handle hit-testing on touches and other related actions that you would need to build yourself if managing a hierarchy of CALayers. It's not that hard to implement this yourself, but it is extra code you'd need to write when building a CALayer-only interface.

You will often need to access the underlying layers for a UIView when performing more complex animations than the base UIView class allows. UIView's animation capabilities have grown as the iOS SDK has matured, but there are still a few things that are best done by interacting with the underlying CALayer.

like image 140
Brad Larson Avatar answered Sep 25 '22 12:09

Brad Larson


From the Ray Wenderlich blog (Tutorial)

CALayers are simply classes representing a rectangle on the screen with visual content. “But wait a darn minute,” you may say, “that’s what UIViews are for!” That’s true, but there’s a trick to that: every UIView contains a root layer that it draws to!

like image 44
Mat Avatar answered Sep 24 '22 12:09

Mat