Instance Method


Returns the default action of the action(forKey:) method.


optional func action(for layer: CALayer, forKey event: String) -> CAAction?



The layer that is the target of the action.


The identifier of the action.

Return Value

An object implementing the CAAction protocol or nil if the delegate does not specify a behavior for the specified key.


A layer's delegate that implements this method returns an action for a specified key and stops any further searches (i.e. actions for the same key in the layer's actions dictionary or specified by defaultAction(forKey:) are not returned).

Listing 1 shows how you can create a class named LayerDelegate that implements CALayerDelegate and sets it as a layer's (named sublayer) delegate. LayerDelegate returns a basic animation that moves an object from left to right. The moveSublayer() method searches sublayer for an action with the key moveRight and, if the action is found, runs it.

Listing 1

Using a layer delegate to return and run an action

let delegate = LayerDelegate()
lazy var sublayer: CALayer = {
    let layer = CALayer()
    layer.delegate = self.delegate
    return layer
func moveSublayer() {
    guard let action = sublayer.action(forKey: "moveRight") else {
    } "transform", object: sublayer, arguments: nil)
class LayerDelegate: NSObject, CALayerDelegate {
    func action(for layer: CALayer, forKey event: String) -> CAAction? {
        guard event == "moveRight" else {
            return nil
        let animation = CABasicAnimation()
        animation.valueFunction = CAValueFunction(name: kCAValueFunctionTranslateX)
        animation.fromValue = 1
        animation.toValue = 300
        animation.duration = 2
        return animation