How to pause and resume UIView.animateWithDuration

前端 未结 3 1669
死守一世寂寞
死守一世寂寞 2020-12-13 07:29

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

UIView.animateWithDuration(10.5, delay:0.0, options: [], animations:{
self.myImage.transform          


        
3条回答
  •  庸人自扰
    2020-12-13 08:09

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

提交回复
热议问题