ios - 如何在 iOS 中为不断闪烁的灯光设置动画?
问题描述
我正在尝试构建一个带有霓虹灯的 iOS 应用程序,它会像真实的一样随机不断地闪烁。
我不完全确定如何让动画不断重复,我不知道如何让它永远自动运行。我把它放在 viewDidLoad 中,但我不确定这是否真的是放置它的最佳位置?
UIImageView.animate(withDuration: 0.05, delay: 5.0, options: .repeat, animations: {
UIImageView.animate(withDuration: 0.05, delay: 2.0, animations: {
self.Aletter.alpha = 0.2
}) { (_) in
UIImageView.animate(withDuration: 0.05, delay: 0.0, animations: {
self.Aletter.alpha = 1.0
}, completion: { (_) in
UIImageView.animate(withDuration: 0.05, delay: 2.0, animations: {
self.Aletter.alpha = 0.6
}, completion: { (_) in
UIImageView.animate(withDuration: 0.05, delay: 0.0, animations: {
self.Aletter.alpha = 1.0
}, completion: { (_) in
UIImageView.animate(withDuration: 0.05, delay: 0.0, animations: {
self.Aletter.alpha = 0.6
}, completion: { (_) in
UIImageView.animate(withDuration: 0.05, delay: 0.0, animations: {
self.Aletter.alpha = 1.0
}, completion: { (_) in
UIImageView.animate(withDuration: 0.05, delay: 0.0, animations: {
self.Aletter.alpha = 0.6
}, completion: { (_) in
UIImageView.animate(withDuration: 0.05, delay: 0.0, animations: {
self.Aletter.alpha = 1.0
}, completion: { (_) in
})
})
})
})
})
})
})
}
})
这段代码将运行我的一系列闪烁,但只运行一次。我需要它持续运行。
解决方案
正如马特在评论部分所建议的那样,您可以使用如下内容:
private func flicker() { [weak self] in
UIView.animate(withDuration: 0.05, animations: {
self?.Aletter.alpha = CGFloat.random(in: 0.1...1.0)
}) { _ in
// When this round of animations completes call the same method again to start the animations again with a new random value for alpha.
self?.flicker()
}
}
只需调用flicker()
您的viewDidLoad()
. flicker
方法启动一个带有随机 alpha 值的动画Aletter
,当这个动画完成时,它会再次调用自己。
作为旁注,对变量使用小的首字母,Aletter
应该aletter
或可能aLetter
基于上下文。
推荐阅读
- python-3.x - 使用 sqlite3 的线程的 Python3 分段错误错误
- pyspark - GCP - GKE 与 Dataproc 上的火花
- session - #pyramid logout 如果正在加载另一个页面,则无法删除会话
- java - 与 Runnable JAR 共享 JDBC 连接
- git - 如何理解 git 子模块功能的工作流程
- java - 用于 Java 的 Firebase
- datetime - 当我得到 endDate.millisecondsSinceEpoch 和 startDate.millisecondsSinceEpoch 之间的差异时,它给了我结果加上 2 小时?
- atg - ATG - 调用 checkFormRedirect 时会话或请求属性为空
- c# - Unity:找不到类型或命名空间名称“函数”
- android-profiler - Android Studio 3.3,Advanced Profiling 对所选进程不可用