Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause and resume UIView.animateWithDuration

Tags:

ios

swift

uiview

I have an image, I animate it with this code, in viewDidAppear:

UIView.animateWithDuration(10.5, delay:0.0, options: [], animations:{
self.myImage.transform = CGAffineTransformMakeTranslation(0.0, 200)
}, completion: nil)

I want to pause the animation when I tap myPauseButton, and resume the animation if I tap it again.

like image 396
Simon Derek Avatar asked Nov 30 '15 08:11

Simon Derek


1 Answers

2 functions to pause and resume animation, I take from here and convert to Swift.

func pauseLayer(layer: CALayer) {
    let pausedTime: CFTimeInterval = layer.convertTime(CACurrentMediaTime(), from: nil)
    layer.speed = 0.0
    layer.timeOffset = pausedTime
}

func resumeLayer(layer: CALayer) {
    let pausedTime: CFTimeInterval = layer.timeOffset
    layer.speed = 1.0
    layer.timeOffset = 0.0
    layer.beginTime = 0.0
    let timeSincePause: CFTimeInterval = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
    layer.beginTime = timeSincePause
}

I have a button to pause or resume the animation which is initiated in viewDidLoad:

var pause = false
override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    UIView.animate(withDuration: 10.5) {
        self.image.transform = CGAffineTransformMakeTranslation(0.0, 200)
    }
}

@IBAction func changeState() {
    let layer = image.layer
    pause = !pause
    if pause {
        pauseLayer(layer)
    } else {
        resumeLayer(layer)
    }
}
like image 197
t4nhpt Avatar answered Nov 15 '22 17:11

t4nhpt