首页 > 解决方案 > 如何在 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

                                    })
                                })
                            })
                        })
                    })
                })
            })
        }
    })

这段代码将运行我的一系列闪烁,但只运行一次。我需要它持续运行。

标签: iosswiftanimation

解决方案


正如马特在评论部分所建议的那样,您可以使用如下内容:

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基于上下文。


推荐阅读