Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

ios - How to pause and resume UIView.animateWithDuration

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...