我的应用程序有一个非常奇怪的问题。我正在使用 UIViewPropertyAnimator
来为内部不断变化的图像制作动画 UIImageView
.
听起来像一个琐碎的任务,但由于某些原因,我的视图最终改变了图像的瞬间,所以我最终以光速闪烁的图像,而不是给定的持续时间和延迟参数。
下面是代码。
private lazy var images: [UIImage?] = [
UIImage(named: "widgethint"),
UIImage(named: "shortcuthint"),
UIImage(named: "spotlighthint")
]
private var imageIndex = 0
private var animator: UIViewPropertyAnimator?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
animator = repeatingAnimator()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
animator?.stopAnimation(true)
}
private func repeatingAnimator() -> UIViewPropertyAnimator {
return .runningPropertyAnimator(withDuration: 2, delay: 6, options: [], animations: {
self.imageView.image = self.images[self.imageIndex]
}, completion: { pos in
if self.imageIndex >= self.images.count - 1 {
self.imageIndex = 0
} else {
self.imageIndex += 1
}
self.animator = self.repeatingAnimator()
})
}
所以,根据代码,动画应该在2秒内完成,并在6秒延迟后开始,但它立即开始,并需要几毫秒来完成,所以我最终用可怕的幻灯片。为什么会出现这种情况?
我也尝试使用 UIViewPropertyAnimator(duration: 2, curve: .linear)
并称 repeatingAnimator().startAnimation(afterDelay: 6)
但结果是一样的。
好吧,我已经想明白了,但是这样简单的任务不能用 "现代 "的动画API来完成还是有点恼火。
所以,在图像里面做动画 UIImageView
显然是不支持的 UIViewPropertyAnimator
在调试过程中,我试着将视图的背景颜色动画化,结果和预期的一样。所以我不得不使用 Timer
取而代之 UIView.transition(with:)
办法
这是工作代码。
private let animationDelay: TimeInterval = 2.4
private var animationTimer: Timer!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setAnimation(true)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
setAnimation(false)
}
private func setAnimation(_ enabled: Bool) {
guard enabled else {
animationTimer?.invalidate()
animationTimer = nil
return
}
animationTimer = Timer.scheduledTimer(withTimeInterval: animationDelay, repeats: true) { _ in
UIView.transition(with: self.imageView, duration: 0.5, options: [.curveLinear, .transitionCrossDissolve], animations: {
self.imageView.image = self.images[self.imageIndex]
}, completion: { succ in
guard succ else {
return
}
if self.imageIndex >= self.images.count - 1 {
self.imageIndex = 0
} else {
self.imageIndex += 1
}
})
}
}
希望以后能省去一些人的麻烦。