当您点击另一个 tabBar 项时viewController
,正在执行动画的项将处于状态viewDidDisappear
并且动画将被删除。
实际上,当 viewController 没有出现在屏幕前面时,不建议执行任何动画。
要继续中断的动画进度,您必须保持动画的当前状态并在 tabBar 项切换回来时恢复它们。
例如,您可以持有一些实例变量来保持动画的持续时间、进度、开始宽度和结束宽度。您可以在以下位置恢复动画viewDidAppear
:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// `self.duration` is the total duration of the animation. In your case, it's 60s.
// `self.progress` is the time that had been consumed. Its initial value is 0s.
// `self.beginWidth` is the inital width of self.progressBarView.
// `self.endWidth`, in your case, is `self.backgroundView.frame.size.width`.
if self.progress < self.duration {
UIView.animateWithDuration(self.duration - self.progress, delay: 0, options: [.CurveLinear], animations: {
self.progressBarView.frame.size.width = CGFloat(self.endWidth)
self.beginTime = NSDate() // `self.beginTime` is used to track the actual animation duration before it interrupted.
}, completion: { finished in
if (!finished) {
let now = NSDate()
self.progress += now.timeIntervalSinceDate(self.beginTime!)
self.progressBarView.frame.size.width = CGFloat(self.beginWidth + self.progress/self.duration * (self.endWidth - self.beginWidth))
} else {
print("progress completed")
}
}
)
}
}