tezvyn:

CATransaction: Grouping Core Animation Changes

AI-drafted, machine-checkedSource: developer.apple.comadvanced
CATransaction: Grouping Core Animation Changes

Think of CATransaction as an atomic 'commit' for UI animations, grouping layer property changes to appear at once. Use it to synchronize animations or set a custom duration for a batch of changes.

WHY IT EXISTS: Core Animation is designed to be efficient. Instead of applying every single property change to the screen immediately, it batches them up to be processed together. CATransaction provides the mechanism to define the boundaries of these batches, ensuring smooth and synchronized visual updates.

THE MENTAL MODEL: CATransaction is like a database transaction for animations. You begin a transaction, make a series of changes to different layer properties (like opacity, position, or color), and then commit the transaction. Core Animation then takes all those changes and animates them together as a single, atomic unit.

HOW IT WORKS: Core Animation maintains a stack of transaction objects for each thread. When you change an animatable layer property, that change is added to the current, top-most transaction. The system automatically creates an "implicit" transaction at the beginning of each run loop cycle and commits it at the end. You can create your own "explicit" transactions by calling CATransaction.begin() to push a new transaction onto the stack and CATransaction.commit() to pop and apply it. You can modify properties of the current transaction, like its duration or a completion block, using class methods like CATransaction.setAnimationDuration(_:).

WHEN TO USE IT: Use explicit transactions when you need fine-grained control that the implicit transaction doesn't offer. For example, to set a different animation duration for a specific group of changes, disable animations for a block of property updates with CATransaction.setDisableActions(_:), or run a piece of code exactly when a set of animations finishes using CATransaction.setCompletionBlock(_:).

WHEN NOT TO USE IT: Avoid creating explicit transactions for simple, single-property animations. The default implicit transaction handling is sufficient and more straightforward for most common cases. Overusing explicit transactions can make code harder to read and debug, especially when nested.

ONE CANONICAL EXAMPLE: To move a layer and fade it out simultaneously over two seconds, you would wrap the changes in an explicit transaction. First, call CATransaction.begin(). Next, call CATransaction.setAnimationDuration(2.0). Then, set the layer's new position and opacity. Finally, call CATransaction.commit(). Both properties will now animate together over the specified two seconds.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.