Swift仅调用X次递归函数

时间:2018-11-29 10:04:07

标签: swift uiview uiviewanimation

我有一个要用来动画4 UILabels的函数。动画是链接在一起的,我正在尝试通过创建一个将标签作为参数接受的递归函数来减少重复的代码,完成后会使用下一个标签自行调用。

   fileprivate func handleAnimations(firstLabel: UILabel, secondLabel: UILabel) -> Void {
        UIView.animate(withDuration: 1, delay: 2, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
            firstLabel.alpha = 1
        }) { (_) in
            UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
                secondLabel.alpha = 1
            }) { (_) in
                UIView.animate(withDuration: 0.5, delay: 3, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: {
                    firstLabel.alpha = 0
                    secondLabel.alpha = 0
                }, completion: { (_) in
                    self.handleAnimations(firstLabel: self.introTextLabelThree, secondLabel: self.introTextLabelFour)
                })
            }
        }
    }

这是实现这一目标的最佳方法吗?如果是这样,我如何防止最终的完整区块用最后的2个标签反复调用自身?

我想要达到的效果是:

labelOne-淡入

labelTwo-淡入

labelOne和labelTwo-淡出

labelThree-淡入

labelFour-淡入

labelThree和labelFour-淡出

在labelThree和labelFour之后,我想实现另一个函数调用。

1 个答案:

答案 0 :(得分:1)

请勿执行此操作。请使用animateKeyframes。这样一来,您就可以正确地链接动画,而不必担心可怕的厄运金字塔。

UIView.animateKeyframes(withDuration: 5.0, delay: 0, options: [.calculationModeCubic], animations: {
        // Add animations
        UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1.0/6.0, animations: {
            self.introTextLabel.alpha = 1
        })
        UIView.addKeyframe(withRelativeStartTime: 1.0/6.0, relativeDuration: 1.0/5.0, animations: {
            self.introTextLabelTwo.alpha = 1
        })
        UIView.addKeyframe(withRelativeStartTime: 2.0/6.0, relativeDuration: 1.0/5.0, animations: {
            self.introTextLabel.alpha = 0
            self.introTextLabelTwo.alpha = 0
        })
        UIView.addKeyframe(withRelativeStartTime: 3.0/6.0, relativeDuration: 1.0/5.0, animations: {
            self.introTextLabelThree.alpha = 1
        })
        UIView.addKeyframe(withRelativeStartTime: 4.0/6.0, relativeDuration: 1.0/5.0, animations: {
            self.introTextLabelFour.alpha = 1
        })
        UIView.addKeyframe(withRelativeStartTime: 5.0/6.0, relativeDuration: 1.0/5.0, animations: {
            self.introTextLabelThree.alpha = 0
            self.introTextLabelFour.alpha = 0
        })
    }, completion:{ _ in
        // fire off whatever other method you want here
    })