John White
John White

Reputation: 253

Swift Completely restart the animation on button click

so what I wanna do is to restart the animation, when it's completed and I pressed the Restart button.

Here's what I've got right now. It starts like that:

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var fillView: UIView!

    @IBAction func startAnimation(sender: AnyObject) {
        self.animationBackground(fillView, animationTime: Float(15))
    }

    @IBAction func restartAnimation(sender: AnyObject) {
        let layerRectangle = fillView.layer
       restartLayer(layerRectangle)
    }

    func animationBackground(view:UIView,animationTime:Float){
        UIView.animateWithDuration(NSTimeInterval(animationTime), delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: {
            view.transform = CGAffineTransformMakeTranslation(0.0,  self.screenSize.height-67)
        },completion:nil)
    }

    func restartLayer(layer:CALayer){
        layer.beginTime = 0.0
        layer.speed = 0.0        
    }
}

The restart function works only while animation is playing. But when it's completed that doesn't restart the animation from the beginning. Any tips on how to restart the animation on button click but only when it's already done?

Upvotes: 1

Views: 2418

Answers (3)

chiarotto.alessandro
chiarotto.alessandro

Reputation: 1589

I have already written above.. by the way:

func animationBackground(view:UIView,animationTime:Float){

     self.fillView.transform = CGAffineTransformIdentity

     UIView.animateWithDuration(NSTimeInterval(animationTime), delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: {
                view.transform = CGAffineTransformMakeTranslation(0.0,  self.screenSize.height-67)
        },completion:nil)
    }

Upvotes: 4

chiarotto.alessandro
chiarotto.alessandro

Reputation: 1589

here the example:

 UIView.animateWithDuration(1, animations: { () -> Void in
     self.fillView.transform = CGAffineTransformMakeTranslation(0, 40)
      }) { (end) -> Void in
             self.fillView.transform = CGAffineTransformIdentity
 }

You can you set transform to CGAffineTransformIdentity just before starting the animation.

Upvotes: 0

chiarotto.alessandro
chiarotto.alessandro

Reputation: 1589

You have tranlsated the position and the frame (position). So once the animation has completed you have to restore the frame to its original position. You can restore the frame in completion block of the animation.

Upvotes: 0

Related Questions