Search code examples
iosswiftuiviewanimationcgaffinetransform

Can't put transform change in animation block of animateWithDuration in Swift


I am trying to change the transform of a layer inside of the animation block of a simple animateWithDuration call in Swift:

UIView.animateWithDuration(0.5, delay: 0.05, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: UIViewAnimationOptions.CurveEaseIn , animations: {
            self.zigZag!.layer.mask.transform = CGAffineTransformMakeTranslation(100, 0)
            }, completion: { (finished: Bool) in
        })

However, this always presents me with the following build error:

Cannot invoke 'animateWithDuration' with an argument list of type '(Double, animations: () -> Void)'

If I delete the trasnform line or replace it with something else like this:

self.zigZag!.center = self.view.center

Then the build error goes away and the app builds just fine.

At this point I'm not sure how I'm supposed to change the transform inside the animation block and get this to build properly.


Solution

  • You could omit the Void -> in altogether in your case; the real culprit that is causing the problem is this line:

    self.zigZag!.layer.mask.transform = CGAffineTransformMakeTranslation(100, 0)
    

    because there is a type mismatch.

    It should be:

    Swift 2

    UIView.animateWithDuration(0.5, delay: 0.05, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: UIViewAnimationOptions.CurveEaseIn, animations: {
       self.view!.layer.mask.transform = CATransform3DMakeTranslation(100.0, 0.0, 0.0)
    }, completion: nil)
    

    Swift 3, 4, 5

    UIView.animate(withDuration: 0.5, delay: 0.05, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: UIView.AnimationOptions.curveEaseIn, animations: {
        self.view!.layer.mask.transform = CATransform3DMakeTranslation(100.0, 0.0, 0.0)
    }, completion: nil)