Swift, проигрывание нескольких анимаций подряд из массива? - PullRequest
0 голосов
/ 19 сентября 2018

Извините, я новичок в Свифте.Я не могу заставить каждую анимацию воспроизводиться последовательно, а не все сразу.Я пытался использовать sleep (), но это, похоже, не позволяет анимации играть.Вот как я нахожу анимацию для воспроизведения.

for number in sequence {
    switch number {
    case 1:
        print("blue")
        animateB()
    case 2:
        print("green")
        animateG()
    case 3:
        print("magenta")
        animateM()
    case 4:
        print("orange")
        animateO()
    case 5:
        print("yellow")
        animateY()
    case 6:
        print("red")
        animateR()
    case 7:
        print("purple")
        animateP()
    case 8:
        print("cyan")
        animateC()
    default:
        print("error")
    }
}

И это одна из функций, которую я использую для анимации.Я понимаю, что, вероятно, это тоже очень неэффективно, но я не был уверен, как сделать функцию лучше.

private func animateB(){
    let animation = CABasicAnimation(keyPath: "transform.scale")
    animation.toValue = 1.3
    animation.duration = 0.5
    animation.autoreverses = true
    self.pulsatingB.add(animation, forKey: "pulsing")
}

Любая помощь будет большой, спасибо.:)

Ответы [ 2 ]

0 голосов
/ 19 сентября 2018

Для последовательности анимаций часто может выполнять работу анимация по ключевым кадрам, например:

UIView.animateKeyframes(withDuration: 4.0, delay: 0, options: .repeat, animations: {
    UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.25, animations: {
        self.subview.transform = .init(scaleX: 0.5, y: 0.5)
    })

    UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.25, animations: {
        self.subview.transform = .init(scaleX: 1.3, y: 1.3)
    })

    UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.25, animations: {
        self.subview.transform = .init(scaleX: 0.75, y: 0.75)
    })

    UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25, animations: {
        self.subview.transform = .identity
    })
}, completion: nil)

Или, если у вас есть массив функций:

let animations = [animateA, animateB, animateC, animateD]

UIView.animateKeyframes(withDuration: 4.0, delay: 0, options: .repeat, animations: {
    for (index, animation) in animations.enumerated() {
        UIView.addKeyframe(withRelativeStartTime: Double(index) / Double(animations.count), relativeDuration: 1 / Double(animations.count), animations: {
            animation()
        })
    }
}, completion: nil)

Где,

func animateA() {
    subview.transform = .init(scaleX: 0.5, y: 0.5)
}

func animateB() {
    subview.transform = .init(scaleX: 1.3, y: 1.3)
}

...
0 голосов
/ 19 сентября 2018

Вы можете использовать CATransaction, чтобы связать CAAnimation s:

class ViewController: UIViewController {

    // The animations, to be applied in order
    var animationQueue = [() -> Void]()

    @IBAction func animate(_ sender: Any) {

        animationQueue.removeAll()

        // Build the animation queue
        for number in sequence {
            switch number {
            case 1:
                print("blue")
                animationQueue.append(animateB)
            case 2:
                print("green")
                animationQueue.append(animateG)
            // ....
            default:
                break
            }
        }

        // Start the animation
        applyNextAnimation()
    }

    func applyNextAnimation() {
        guard !animationQueue.isEmpty else { return }
        let animation = animationQueue.removeFirst()

        // When an animation completes, call this function again to apply the next animation
        CATransaction.begin()
        CATransaction.setCompletionBlock({ self.applyNextAnimation() })
        animation()
        CATransaction.commit()
    }

}
...