我通过增加一个简单的图像来制作进度条:
let progressBar = createProgressBar(width: self.view.frame.width, height: 60.0)
let progressBarView = UIImageView(image: progressBar)
progressBarView.frame = CGRect(x: 0, y: 140, width: 0, height: 60)
UIView.animateWithDuration(60.0, delay: 0.0, options: [], animations: {
progressBarView.frame.size.width = self.backgroundView.frame.size.width
}, completion: {_ in
print("progress completed")
}
)
这可以按预期工作,但是在使用TabBarController更改视图时遇到问题。当我更改视图时,我希望进度条在后台继续动画,这样我可以返回到此视图来检查进度,但是当我更改视图时它会立即结束,并且调用完成块。
为什么会发生这种情况,以及如何解决这个问题?
答案 0 :(得分:0)
当您点按另一个tabBar项目时,正在执行动画的viewController
将处于viewDidDisappear
状态,并且动画将被删除。
实际上,当viewController未显示在屏幕前方时,建议不要执行任何动画。
要继续中断的动画进度,您必须保持动画的当前状态,并在tabBar项目切换回来时恢复它们。
例如,您可以保留一些实例变量来保持动画的持续时间,进度,beginWidth和endWidth。您可以在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")
}
}
)
}
}