我正在尝试构建一个霓虹灯的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
})
})
})
})
})
})
})
}
})
此代码将运行我的一系列闪烁,但仅运行一次。我需要它不断前进。
答案 0 :(得分:1)
如马特(Matt)在评论部分中所建议的,您可以使用类似以下的内容:
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
方法使用Aletter
视图的随机alpha值启动动画,并在动画完成后再次调用自身。
请注意,根据变量,使用小写的首字母,Aletter
应该是aletter
或aLetter
,具体取决于上下文。