如何暂停和恢复UIView.animateWithDuration
我有一个图像,我使用此代码为viewDidAppear设置动画:
UIView.animateWithDuration(10.5, delay:0.0, options: [], animations:{ self.myImage.transform = CGAffineTransformMakeTranslation(0.0, 200) }, completion: nil)
我想点击myPauseButton
时暂停动画,如果我再次点击它,则恢复动画。
暂停和恢复动画的2个function,我从这里开始转换为Swift。
func pauseLayer(layer: CALayer) { let pausedTime: CFTimeInterval = layer.convertTime(CACurrentMediaTime(), fromLayer: 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(), fromLayer: nil) - pausedTime layer.beginTime = timeSincePause }
我有一个按钮来暂停或恢复在viewDidLoad
初始化的动画:
var pause = false override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) UIView.animateWithDuration(10.5, delay:0.0, options: [], animations:{ self.image.transform = CGAffineTransformMakeTranslation(0.0, 200) }, completion: nil) } @IBAction func changeState() { let layer = image.layer pause = !pause if pause { pauseLayer(layer) } else { resumeLayer(layer) } }
这是答案的Swift 3版本+我将这些function移到了扩展名
extension CALayer { func pause() { let pausedTime: CFTimeInterval = self.convertTime(CACurrentMediaTime(), from: nil) self.speed = 0.0 self.timeOffset = pausedTime } func resume() { let pausedTime: CFTimeInterval = self.timeOffset self.speed = 1.0 self.timeOffset = 0.0 self.beginTime = 0.0 let timeSincePause: CFTimeInterval = self.convertTime(CACurrentMediaTime(), from: nil) - pausedTime self.beginTime = timeSincePause } }
由于iOS 10提供了UIViewPropertyAnimator
您可以更轻松地解决问题。
在控制器中创建这些属性:
var animationPaused = false lazy var animator: UIViewPropertyAnimator = UIViewPropertyAnimator(duration: 10.5, curve: .easeInOut, animations: { self.myImage.transform = CGAffineTransform(translationX: 0.0, y: 200) })
将以下代码添加到myPauseButton
的tap处理程序中:
if self.animator.state == .active { // Don't start or pause animation when it finished self.animationPaused = !self.animationPaused self.animationPaused ? self.animator.pauseAnimation() : self.animator.startAnimation() }
使用以下代码行从viewDidAppear(_ animated: Bool)
开始动画:
self.animationPaused = false self.animator.startAnimation()
- 我怎么能animation的UIViewController推UINavigationBar背景更改?
- 下载cydia和越狱iOS 11
- Objective C UIImagePNGRepresentation内存问题(使用ARC)
- ABMultiValueGetCount – kABPersonSocialProfileProperty总是返回0? 我怎样才能从地址簿获得Facebook的细节?
- 我如何设置xcodebuild的输出目录?
- 如何从我的应用程序打开缩短的Google Maps URL?
- iOS AVFoundation – 将video转换为60 fps的图像
- 如何解决在UIViewController已经离开时调用viewDidScroll的bug?
- 无法从其他线程删除Realm数据库对象(即使search后)