Search code examples
iosswiftuiviewuiviewanimationcgaffinetransform

How to access radius dynamically during animation? (possible during CGAffineTransform)


I'm using two simple CGAffineTransforms to scale a circular UIView up and back down again, but I'd like to be able to dynamically access the radius in touchesBegan() while the animation is happening and check if it equals a certain value at that point.

The difficulty is that I need to check the radius while the animation is still happening. I'm not completely sold on the CGAffineTransforms approach, so I'm more than happy to animate the circle in another way if it would mean being able to access the radius. Thank you!

I'm at a loss on how to do that. Here is my code below (tips welcome!):

func grow() {

    UIView.animateWithDuration(2.3, delay: 0.0,
        options: UIViewAnimationOptions.CurveEaseIn,
        animations: {
            self.circle2.transform = CGAffineTransformMakeScale(1.5, 1.5)
        },
        completion: ({ finished in
            if (finished) {
                self.shrink()
            }
        }))
}

func shrink() {

    UIView.animateWithDuration(2.3, delay: 0.0,
        options: UIViewAnimationOptions.CurveEaseInOut,
        animations: {
            self.circle2.transform = CGAffineTransformMakeScale(0.5, 0.5)
        },
        completion: ({ finished in
            if (finished) {
                self.grow()
            }
        }))
}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        /*
        if radius == certain value
            {
                //do something
            }
        */
    }

Solution

  • First, I would recommend doing this animation using a plain CABasicAnimation or CAKeyframeAnimation, because you can use anim.repeatCount = .infinity rather than completion handlers that call each other back and forth.

    The current state of the animation can be accessed by circle2.layer.presentationLayer. As mentioned in this question, you can use its frame which will take the transform into account.