ios - UIViewPropertyAnimator 不尊重持续时间和延迟参数
问题描述
我的应用程序中有一个非常奇怪的问题。我用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)
and 调用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
}
})
}
}
希望它会在未来为某人省去一些麻烦
推荐阅读
- java - 在配置中设置 jdkhome 后 Netbeans 不会启动
- python - Python Dataframe 查找日期时间行之间的差异并转换为秒
- java - Primefaces menuButton 在版本更新 6.2 -> 7.0 后不起作用
- powershell - 带有文件夹排除的设置 ACL
- typescript - 打字稿泛型、约束和文字类型
- amazon-web-services - AWS Step Functions - 在不发生迭代时利用空 Map 状态输出
- python - google 的 python 风格指南 - 属性说明
- arrays - 如何在 Kotlin 中从单个字符串创建字符串数组
- javascript - Socket.io - React:如何显示房间中连接的用户?
- python - Python 请求问题 self._store[key.lower()][1]