Search code examples
ioscocoa-touchios-animations

How to use perform(aSelector: , with: , afterDelay: , inModes: ) to pause a CABasicAnimation after a delay


I am using perform(aSelector: , with: , afterDelay: , inModes: ) to pause an animation after a specified delay. However, I keep getting an Unrecognized Selector Error. I am not sure what could possibly be causing this.

Sample Code (Updated):

    class ExpandingSelectedLayer: CALayer, CAAnimationDelegate
    {

    let expandingAnim = CABasicAnimation(keyPath: #keyPath(CALayer.bounds))
expandingAnim.perform(#selector(expandingAnim.pauseAnim), with: nil, afterDelay: 2.0, inModes: [RunLoopMode.commonModes])
    }


    extension CABasicAnimation 
    {
            @objc func pauseAnim()
            {
                print("called pause Anim")
                self.speed = 0

            }
    }

Solution

  • First: the anArgument argument in perform(_:with:afterDelay:) is the argument to pass to the method. The selector in your question doesn't take any arguments but your perform call is passing it an argument. Since pauseAnim doesn't take any arguments you would just pass nil for the anArgument argument.

    Second: It's not clear from your question where the pauseAnim method is defined. Unless it's a method on CABasicAnimation (or somewhere in its class hierarchy) you won't be able to call that method on an instance of CABasicAnimation. If this method is defined on a view controller or other object you would use that as the receiver instead (possibly self).